package com.atlassian.stash.internal.license;

import com.atlassian.cache.CacheFactory;
import com.atlassian.cache.memory.MemoryCacheManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class DefaultLicenseCacheTest {

    @Spy
    private CacheFactory cacheFactory = new MemoryCacheManager();
    @Mock
    private DualLicense license;
    @InjectMocks
    private DefaultLicenseCache licenseCache;
    @Mock
    private LicenseHelper licenseHelper;

    @Test
    public void getNotSet() throws Exception {
        assertEquals(empty(), licenseCache.get());
    }

    @Test
    public void get() throws Exception {
        when(licenseHelper.getDecoded()).thenReturn(license);

        assertEquals(license, licenseCache.get().get());
    }

    @Test
    public void getAsStringNotSet() throws Exception {
        assertEquals(empty(), licenseCache.getAsString());
    }

    @Test
    public void getAsString() throws Exception {
        when(licenseHelper.getDecoded()).thenReturn(license);

        String licenseString = "license";
        when(license.getEncodedLicense()).thenReturn(licenseString);

        assertEquals(licenseString, licenseCache.getAsString().get());
    }

    @Test
    public void reset() throws Exception {
        when(licenseHelper.getDecoded()).thenReturn(license);

        assertEquals(of(license), licenseCache.get());

        DualLicense license2 = mock(DualLicense.class);
        when(licenseHelper.getDecoded()).thenReturn(license2);

        licenseCache.reset();

        assertEquals(license2, licenseCache.get().get());
    }
}