package io.ljunggren.dhl.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.ljunggren.dhl.api.model.Debug;
import io.ljunggren.json.utils.JsonUtils;

public class BaseService {

    protected String domain;
    protected String apiKey;
    
    protected BaseService(String domain, String apiKey) {
        this.domain = domain;
        this.apiKey = apiKey;
    }

    protected CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD).build())
                .build();
    }
    
    protected static Debug debug(HttpRequestBase httpRequest, CloseableHttpClient httpClient, Debug debug) throws IOException {
        debug.setMethod(httpRequest.getMethod());
        debug.setUrl(httpRequest.getURI().toString());
        try {
            try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
                debug.setResponseCode(response.getStatusLine().getStatusCode());
                debug.setResponse(getResult(response));
            }
        } catch (IOException e) {
            debug.setResponse("Request failed: " + e.getMessage());
        } finally {
            httpClient.close();
        }
        return debug;
    }

    protected static String getResult(HttpResponse response) throws IOException {
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        }
    }

    protected <T> T parse(String json, Class<T> clazz) throws IOException {
        try {
            return JsonUtils.jsonToObject(json, clazz);
        } catch (JsonProcessingException e) {
            throw new IOException("Unable to parse response", e);
        }
    }
}
