package ru.yandex.inside.goals;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.ws.rs.core.Response;

import com.fasterxml.jackson.databind.ObjectReader;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.utils.URIBuilder;

class HttpUtil {

    private final GoalsClient client;

    public HttpUtil(GoalsClient client) {
        this.client = client;
    }

    <T> T doGetRequest(URIBuilder uriBuilder, ObjectReader objectReader) throws ClientProtocolException {
        try {
            uriBuilder.addParameter("format", "json");

            final Response response = client.getHttpClient()
                    .create(uriBuilder, client.getToken())
                    .get();

            if (HttpStatus.SC_FORBIDDEN == response.getStatus()){
                throw new HttpResponseException(response.getStatus(), "HttpStatus = [" + response.getStatus() + "], please token token value in env.GOAL_OAUTH_TOKEN");
            } else if (response.getStatus() != HttpStatus.SC_OK) {
                throw new HttpResponseException(response.getStatus(), "HttpStatus = [" + response.getStatus() + "]!");
            }

            if (!response.hasEntity()) {
                throw new ClientProtocolException("No content");
            }

            return objectReader.readValue(response.readEntity(String.class));

        } catch (IOException | URISyntaxException e) {
            throw new ClientProtocolException(e);
        }
    }
}
