package com.atlassian.bitbucket.test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

import static javax.ws.rs.core.Response.Status.NO_CONTENT;
import static javax.ws.rs.core.Response.Status.OK;

public class BatchNotificationTestHelper {

    private static final int FLUSH_SETTLE_DELAY = 500;

    /**
     * Return the number of user notification objects in the queue - note that this
     * does not necessarily correspond to the number of emails that will be sent, or
     * the number of activities that are in the email, but is rather a raw count of objects
     * that are ready to be processed.
     *
     * @return number of user notifications queued
     */
    public static int getBatchNotificationCount() {
        Response response = RestAssured
                .expect()
                    .contentType(ContentType.JSON)
                    .statusCode(OK.getStatusCode())
                .given()
                    .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                    .get(DefaultFuncTestData.getRestURL("notification", "latest") + "/batch");

        return response.body().jsonPath().getInt("count");
    }

    public static void flushBatchNotificationQueue() throws InterruptedException {
        /*
         * Very rarely when we flush the queue the event we want to see the email for hasn't yet processed and so there
         * are intermittent test errors.  The rationale for introducting a small delay here instead of any other options
         * are:
         *
         * 1. This happens rarely, most of the times the events process fast, so a small delay should eliminate flakiness
         * without a major impact to test runtime
         *
         * 2. Other options would involve actually inspecting the queue to ensure the event was processed before flushing
         * the queue - this seems overly complex, and not a function that would be useful outside of these tests.
         */
        Thread.sleep(FLUSH_SETTLE_DELAY);

        long time = System.currentTimeMillis() + (60 * 60 * 1000); // 1 hour in the future should be plenty
        RestAssured
                .given()
                    .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType(ContentType.JSON)
                .when()
                    .post(DefaultFuncTestData.getRestURL("notification", "latest") + "/batch/process?time=" + time)
                .then()
                    .statusCode(NO_CONTENT.getStatusCode())
                .log().ifValidationFails();
    }
}
