package com.atlassian.bitbucket.internal.tag.idx;

import com.atlassian.bitbucket.repository.RefService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import com.google.common.collect.ImmutableSet;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.File;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class TagIndexerTest {

    @Rule
    public final TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Mock
    private ApplicationPropertiesService propertiesService;

    @Mock
    private RefService refService;

    private File cacheDir;

    @Before
    public void setUp() throws Exception {
        cacheDir = temporaryFolder.newFolder();
        when(propertiesService.getCacheDir()).thenReturn(cacheDir);
    }

    @SuppressWarnings("ConstantConditions")
    @Test
    public void testIndexer() throws Exception {
        ImmutableSet<String> testHashSet = ImmutableSet.of("06e4eb0e1167c819ce9e8a59f28611567ecf5a56");

        File tagCache = new File(cacheDir, "tag-index");
        assertTrue(tagCache.mkdir());
        assertNotNull(File.createTempFile("cache-entry", "", tagCache));

        // Check the indexer removes any stale entry when initialised
        TagIndexer indexer = new TagIndexer(propertiesService, refService);
        indexer.init();
        assertEquals(0, tagCache.listFiles().length);

        indexer.readIndex(mock(Repository.class), 25, testHashSet);
        assertEquals(1, tagCache.listFiles().length);

        // Check the indexer removes the cache entries when destroyed
        indexer.destroy();
        assertEquals(0, tagCache.listFiles().length);

        // Check the indexer does not create any new stale entry if a caller attempts to read the index after destruction
        indexer.readIndex(mock(Repository.class), 25, testHashSet);
        assertEquals(0, tagCache.listFiles().length);
    }
}
