package it.com.atlassian.bitbucket.integrity;

import com.atlassian.bitbucket.test.DefaultFuncTestData;
import com.atlassian.pageobjects.ProductInstance;
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.path.json.JsonPath;

public class IntegrityTestUtils {

    public static long getValue(ProductInstance instance, String key) {
        String url = urlFor(instance, DefaultFuncTestData.getRestURL())
                .concat("/users/" + DefaultFuncTestData.getAdminUser() + "/settings");
        JsonPath jsonPath = RestAssured.expect()
                    .statusCode(200)
                .given()
                    .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .when()
                    .get(url)
                .then()
                    .log().body()
                .extract()
                    .jsonPath();
        try {
            return jsonPath.getLong(key);
        } catch (Exception ex) {
            throw new AssertionError("Unable to retrieve key [" + key +
                    "] from JSON message [\n" + jsonPath.prettify() + "\n] retrieved from [" + url + "]", ex);
        }
    }

    public static String urlFor(ProductInstance instance, String url) {
        return url.replace(DefaultFuncTestData.getBaseURL(), instance.getBaseUrl())
                .replace("7990", String.valueOf(instance.getHttpPort()))
                .replace("/bitbucket/", instance.getContextPath() + "/");
    }
}
