package com.atlassian.bitbucket.test;

import com.jayway.restassured.RestAssured;
import net.sf.json.JSONObject;

import javax.ws.rs.core.MediaType;

import static org.hamcrest.collection.IsIn.isOneOf;

public class ApplicationLinkTestHelper {

    public static String createApplicationLink(String type, String name, String displayUrl, String rpcUrl, boolean isPrimary) throws Exception {
        JSONObject json = new JSONObject();
        json.put("applicationLink", createApplicationLinkJSON(type, name, displayUrl, rpcUrl, isPrimary));
        json.put("configFormValues", createConfigFormValuesJson(false, false));

        return RestAssured
                .given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .body(json.toString())
                .contentType(MediaType.APPLICATION_JSON)
                .header("Accept", MediaType.APPLICATION_JSON)
                .expect()
                .statusCode(isOneOf(200, 201))
                .when()
                .post(DefaultFuncTestData.getBaseURL() + "/rest/applinks/1.0/applicationlinkForm/createAppLink")
                .body().jsonPath().getString("applicationLink.id");
    }

    public static JSONObject createApplicationLinkJSON(String type, String name, String displayUrl, String rpcUrl, boolean isPrimary) throws Exception {
        final JSONObject json = new JSONObject();
        json.put("typeId", type);
        json.put("name", name);
        json.put("displayUrl", displayUrl);
        json.put("rpcUrl", rpcUrl);
        json.put("isPrimary", isPrimary);

        return json;
    }

    public static JSONObject createConfigFormValuesJson(boolean trustEachother, boolean shareUserbase) {
        JSONObject configFormValuesJson = new JSONObject();
        configFormValuesJson.put("trustEachOther", trustEachother);
        configFormValuesJson.put("shareUserbase", shareUserbase);

        return configFormValuesJson;
    }

    public static void deleteApplicationLink(String id) {
        RestAssured
                .expect()
                .statusCode(isOneOf(200, 201))
                .given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .when()
                .delete(DefaultFuncTestData.getBaseURL() + "/rest/applinks/1.0/applicationlink/" + id);
    }

}
