package it.com.atlassian.stash.rest.scm.git.lfs;

import com.atlassian.bitbucket.async.AsyncTestUtils;
import com.atlassian.bitbucket.async.WaitCondition;
import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.bitbucket.test.GitLfsTestHelper;
import org.hamcrest.Description;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class GitLfsForkTest extends BaseGitLfsRestTest {

    private static final String TEST_PROJECT = DefaultFuncTestData.getProject1();
    private static final String TEST_REPO = DefaultFuncTestData.getProject1Repository1();
    private static final String TEST_ORIGIN = "origin";
    private static final String TEST_FORK = "fork";

    @Before
    public void setUp() {
        testContext.forkNonPersonal(TEST_PROJECT, TEST_REPO, TEST_PROJECT, TEST_ORIGIN);
    }

    @Test
    public void testForkMatchesOriginLfsDisabled() {
        runTest(false);
    }

    @Test
    public void testForkMatchesOriginLfsEnabled() {
        runTest(true);
    }

    /**
     * @param lfsEnabledOnOrigin the state of the "LFS Enabled" checkbox on the origin prior to the
     *                           fork being created. This is then also the expected state of the same
     *                           checkbox on the fork.
     */
    private void runTest(boolean lfsEnabledOnOrigin) {
        // Configure origin
        if (lfsEnabledOnOrigin) {
            GitLfsTestHelper.enable(TEST_PROJECT, TEST_ORIGIN);
        } else {
            GitLfsTestHelper.disable(TEST_PROJECT, TEST_ORIGIN);
        }
        assertEquals(lfsEnabledOnOrigin, GitLfsTestHelper.isEnabled(TEST_PROJECT, TEST_ORIGIN));

        // Create fork
        testContext.forkNonPersonal(TEST_PROJECT, TEST_ORIGIN, TEST_PROJECT, TEST_FORK);

        // Verify - Because the RepositoryForkedEvent is asynchronous the application of
        // the correct settings may not be instantaneous
        long timeoutMs = 1000;
        AsyncTestUtils.waitFor(new WaitCondition() {
            @Override
            public boolean test() throws Exception {
                return GitLfsTestHelper.isEnabled(TEST_PROJECT, TEST_FORK) == lfsEnabledOnOrigin;
            }

            @Override
            public void describeFailure(Description description) throws Exception {
                description.appendText("Fork does not have same 'isEnabled' setting as origin after " + timeoutMs + "ms");
            }
        }, timeoutMs);
    }
}
