package be.ehealth.technicalconnector.cache;

import static be.ehealth.technicalconnector.cache.CacheFactory.CacheType.MEMORY;
import static be.ehealth.technicalconnector.cache.CacheFactory.CacheType.PERSISTENT;
import static be.fgov.ehealth.technicalconnector.bootstrap.bcp.domain.CacheInformation.ExpiryType.NONE;

import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.fgov.ehealth.technicalconnector.tests.utils.LoggingUtils;

/**
 * Unit test to verify the behaviour of the {@link CacheFactory}
 *
 * @author EHP
 */
public class CacheFactoryTest {

    private static final Logger LOG = LoggerFactory.getLogger(CacheFactoryTest.class);

    private Cache<String, String> memoryCache = CacheFactory.newInstance(MEMORY, "cache-factory-memory", null, null);
    private Cache<String, String> persistentCache = CacheFactory.newInstance(PERSISTENT, "cache-factory-persists", NONE, null);


    @BeforeClass
    public static void before() {
        LoggingUtils.bootstrap();
    }

    @Test
    public void notNull() throws Exception {
        Assert.assertNotNull(memoryCache);
        Assert.assertNotNull(persistentCache);
    }

    @Test
    public void memoryCacheVerify() throws Exception {
        memoryCache.put("entry", "value");
        Assert.assertEquals("value", memoryCache.get("entry"));
        memoryCache.remove("entry");
        Assert.assertNull(memoryCache.get("entry"));
    }

    @Test
    public void memoryCacheClear() throws Exception {
        memoryCache.put("entry", "value");
        Assert.assertEquals("value", memoryCache.get("entry"));
        memoryCache.clear();
        Assert.assertNull(memoryCache.get("entry"));
    }

    @Test
    public void persistentCacheVerify() throws Exception {
        persistentCache.put("entry", "value");
        Assert.assertEquals("value", persistentCache.get("entry"));
        persistentCache.remove("entry");
        Assert.assertNull(persistentCache.get("entry"));
    }

    @Test
    public void persistVerify() {
        final String result = persistentCache.get("persist-entry");
        if (result == null) {
            LOG.warn("First run of the test setting up persistent storage entry!");
            persistentCache.put("persist-entry", "value");
            Assume.assumeNotNull(result);
        } else {
            Assert.assertEquals("value", result);
        }
    }

}