package com.atlassian.bitbucket.scm.cache.internal;

import com.atlassian.bitbucket.permission.PermissionValidationService;
import com.atlassian.bitbucket.project.Project;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.util.contentcache.ContentCache;
import com.atlassian.util.contentcache.ContentCacheManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertSame;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class DefaultScmCacheServiceTest {
    @Mock
    private ContentCache cache;
    @Mock
    private ContentCacheManager cacheManager;
    @Mock
    private ClusterNotificationService notificationService;
    @Mock
    private PermissionValidationService permissionValidationService;
    @InjectMocks
    private DefaultScmCacheService service;

    @Before
    public void setup() {
        when(cacheManager.getCache(anyString())).thenReturn(cache);
    }

    @Test
    public void testClear() {
        service.clear();

        verify(cacheManager).clear();
    }

    @Test
    public void testClearEntry() {
        Repository repo = mockRepo("PKEY", "slug");
        service.clear(repo, "key");

        verify(cacheManager).getCache("99");
        verify(cache).remove("key");
    }

    @Test
    public void testClearRepoCache() {
        Repository repo = mockRepo("PKEY", "slug");
        service.clear(repo);

        verify(cacheManager).getCache("99");
        verify(cache).clear();
    }

    @Test
    public void testGetCache() {
        assertSame(cacheManager, service.getCacheManager());
    }

    @Test
    public void testGetStatistics() {
        service.getStatistics();

        verify(cacheManager).getStatistics();
    }

    @Test
    public void testGetRepoStatistics() {
        Repository repo = mockRepo("PKEY", "slug");
        service.getStatistics(repo);

        verify(cacheManager).getCache("99");
        verify(cache).getStatistics();
    }

    private Repository mockRepo(String projectKey, String slug) {
        Repository repo = mock(Repository.class);
        Project project = mock(Project.class);

        when(repo.getId()).thenReturn(99);
        when(repo.getSlug()).thenReturn(slug);
        when(project.getKey()).thenReturn(projectKey);
        when(repo.getProject()).thenReturn(project);

        return repo;
    }


}
