package it.com.atlassian.stash.scheduling;

import com.atlassian.scheduler.config.RunMode;
import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.bitbucket.test.annotations.CompatibleWithProductTopologies;
import com.google.common.collect.ImmutableList;
import com.jayway.restassured.RestAssured;
import it.com.atlassian.stash.BaseRestTest;
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runners.Parameterized;

import static com.atlassian.bitbucket.test.ProductTopology.BITBUCKET_STANDALONE;
import static org.hamcrest.Matchers.*;

//CountingJobRunner stores its run count and count down latches in memory
@CompatibleWithProductTopologies(BITBUCKET_STANDALONE)
public class SchedulerTest extends BaseRestTest {

    @Parameterized.Parameters(name = "{0}/{1}")
    public static Iterable<Object[]> parameters() {
        ImmutableList.Builder<Object[]> builder = ImmutableList.builder();
        for (RunMode runMode : RunMode.values()) {
            builder.add(new Object[]{"SchedulerTest.cron", runMode, greaterThanOrEqualTo(2)});
            builder.add(new Object[]{"SchedulerTest.interval", runMode, greaterThanOrEqualTo(2)});
            builder.add(new Object[]{"SchedulerTest.once", runMode, equalTo(1)});
        }
        return builder.build();
    }

    @Parameterized.Parameter(0)
    public String jobPrefix;

    @Parameterized.Parameter(1)
    public RunMode runMode;

    @Parameterized.Parameter(2)
    public Matcher<Integer> countMatcher;

    // Timeout after 3 minutes. This should be worst case scenario. Hopefully this test runs at the end of the rest
    // tests so it doesn't take this long
    @Test(timeout = 180000)
    public void testScheduler() throws Exception {
        RestAssured.given()
                .contentType("application/json")
                .expect()
                .statusCode(200)
                .body("count", countMatcher)
                .log().ifStatusCodeMatches(not(200))
                .when()
                .get(DefaultFuncTestData.getBaseURL() + "/rest/rest-tests/latest/scheduler/" + jobPrefix + "/" + runMode.name());
    }
}
