package com.atlassian.bitbucket.test;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import net.sf.json.JSONObject;
import org.junit.Ignore;

import javax.ws.rs.core.MediaType;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

@Ignore
public class SshKeyTestHelper {

    public static Response addSshKey(String username, String keyText) {
        Response response = RestAssured
                .given()
                .queryParam("user", username)
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType(MediaType.APPLICATION_JSON + ";charset=UTF-8")
                .body(createSshKeyBody(keyText).toString())
                .when()
                .post(DefaultFuncTestData.getRestURL("ssh", "latest") + "/keys");

        assertThat("Expected 2xx status code when creating an ssh key", response.getStatusCode(),
                allOf(greaterThanOrEqualTo(200), lessThan(300)));
        return response;
    }

    public static Response removeSshKey(Integer keyId) {
        Response response = RestAssured
                .given()
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType(MediaType.APPLICATION_JSON + ";charset=UTF-8")
                .when()
                .delete(DefaultFuncTestData.getRestURL("ssh", "latest") + "/keys/{id}", keyId);

        assertThat("Expected 2xx status code when deleting ssh key", response.getStatusCode(),
                allOf(greaterThanOrEqualTo(200), lessThan(300)));
        return response;
    }

    public static Response removeSshKeys(String username) {
        Response response = RestAssured
                .given()
                .queryParam("user", username)
                .auth().preemptive().basic(DefaultFuncTestData.getAdminUser(), DefaultFuncTestData.getAdminPassword())
                .contentType(MediaType.APPLICATION_JSON + ";charset=UTF-8")
                .when()
                .delete(DefaultFuncTestData.getRestURL("ssh", "latest") + "/keys");

        assertThat("Expected 2xx status code when deleting all ssh keys", response.getStatusCode(),
                allOf(greaterThanOrEqualTo(200), lessThan(300)));
        return response;
    }

    private static JSONObject createSshKeyBody(String keyText) {
        JSONObject bodyObject = new JSONObject();

        bodyObject.put("text", keyText);
        return bodyObject;
    }
}
