package com.atlassian.bitbucket.mesh.repository;

import com.atlassian.bitbucket.mesh.clock.TickingClock;
import com.atlassian.bitbucket.mesh.junit.TemporaryDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;

import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class DefaultWorkTreeTest {

    private static final Duration EXPIRY_DURATION = Duration.ofMinutes(5L);

    @Rule
    public final TemporaryDirectory tempDir = new TemporaryDirectory();

    private TickingClock clock;
    private Instant expiry;
    @Mock
    private Repository repository;
    private WorkTree workTree;
    private Path workTreePath;

    @Before
    public void setUp() throws Exception {
        clock = new TickingClock();
        expiry = clock.instant().plus(EXPIRY_DURATION);
        long workTreeId = System.currentTimeMillis();

        workTreePath = tempDir.newFolder("worktree-" + workTreeId);
        workTree = new DefaultWorkTree(clock, expiry, false, workTreeId, workTreePath, repository);
    }

    @Test
    public void testBasicProperties() {
        assertEquals(expiry, workTree.getExpiry());
        assertEquals(workTreePath, workTree.getPath());
        assertEquals(repository, workTree.getRepository());
    }

    @Test
    public void testIsExpired() {
        assertFalse(workTree.isExpired());
        //1ms before expiry
        clock.tick(EXPIRY_DURATION.minus(Duration.ofMillis(1L)));
        assertFalse(workTree.isExpired());
        clock.tick(Duration.ofMillis(1L));
        assertTrue(workTree.isExpired());
    }
}
