package ru.stqa.pft.rest;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jayway.restassured.RestAssured;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;

import java.io.IOException;
import java.util.Set;

/**
 * Created by Serg on 01.02.2017.
 */
public class TestBase {

    @BeforeClass
    public void init() {
        RestAssured.authentication = RestAssured.basic("LSGjeU4yP1X493ud1hNniA==", "");
    }

    protected Set<Issue> getIssues() throws IOException {
        String json = RestAssured.get("http://demo.bugify.com/api/issues.json").asString();
        JsonElement parsed = new JsonParser().parse(json);
        JsonElement issues = parsed.getAsJsonObject().get("issues");
        return new Gson().fromJson(issues, new TypeToken<Set<Issue>>(){}.getType());
    }

    protected int createIssue(Issue newIssue) throws IOException {
        String json = RestAssured.given()
                .parameter("subject", newIssue.getSubject())
                .parameter("description", newIssue.getDescription())
                .post("http://demo.bugify.com/api/issues.json").asString();
        JsonElement parsed = new JsonParser().parse(json);
        return parsed.getAsJsonObject().get("issue_id").getAsInt();
    }

    public boolean isIssueOpened (int issueId) {
        String issue = getIssueById(issueId);
        if (issue.equals("Closed") || issue.equals("Resolved")) {
            return false;
        }
        return true;
    }

    private String getIssueById(int issueId) {
        String json = RestAssured.get(String.format("http://demo.bugify.com/api/issues/%s.json", issueId))
                .asString();
        JsonElement parsed = new JsonParser().parse(json);
        return parsed.getAsJsonObject().get("issues").getAsJsonArray().get(0)
                .getAsJsonObject().get("state_name").getAsString();
    }

    protected void skipIfNotFixed(int issueId) {
        if (isIssueOpened(issueId)) {
            throw new SkipException("Ignored because of issue " + issueId);
        }
    }
}
