package io.ljunggren.usps.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import org.apache.http.Header;
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 org.apache.http.message.BasicHeader;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import io.ljunggren.json.utils.JsonUtils;
import io.ljunggren.usps.api.model.Debug;

public class BaseService {

    protected static final int CONNECT_TIMEOUT_MS = 5000;
    protected static final int SOCKET_TIMEOUT_MS = 15000;

    protected String domain;

    protected BaseService(String domain) {
        this.domain = domain;
    }

    protected CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setCookieSpec(CookieSpecs.STANDARD)
                        .setConnectTimeout(CONNECT_TIMEOUT_MS)
                        .setConnectionRequestTimeout(CONNECT_TIMEOUT_MS)
                        .setSocketTimeout(SOCKET_TIMEOUT_MS)
                        .build())
                .build();
    }
    
    protected static Debug debug(HttpRequestBase httpRequest, CloseableHttpClient httpClient, Debug debug) throws IOException {
    	try {
    		debug.setMethod(httpRequest.getMethod());
    		debug.setUrl(httpRequest.getURI().toString());
    		try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
    		    debug.setResponseCode(response.getStatusLine().getStatusCode());
                debug.setResponse(getResult(response));
    		}
    	} catch(Exception e) {
    		debug.setResponse(e.getMessage());
    	} finally {
            httpClient.close();
        }
    	return debug;
    }

    protected static String getResult(HttpResponse response) throws UnsupportedOperationException, IOException {
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        StringBuilder result = new StringBuilder();
        String line = new String();
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        return result.toString();
    }
    
    private static final ObjectMapper MAPPER = createMapper();

    private static ObjectMapper createMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        return mapper;
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }
    
    protected <T> T parse(String json, Class<T> clazz) throws Exception {
        try {
            return JsonUtils.jsonToObject(json, clazz, getMapper());
        } catch (JsonProcessingException e) {
            throw new Exception("Unable to parse response");
        }
    }
    
    protected <T> List<T> parseList(String json, Class<T> clazz) throws Exception {
    	try {
    		return JsonUtils.jsonToList(json, clazz, getMapper());
        } catch (JsonProcessingException e) {
            throw new Exception("Unable to parse response");
        }
    }
    
    protected void throw429() throws Exception {
        throw new Exception("Too many request, try again later");
    }

    protected void checkForError(int responseCode, String json) throws Exception {
        if (responseCode < 200 || responseCode >= 300) {
            throw new Exception("USPS API request failed with status " + responseCode + ": " + json);
        }
    }

    protected static Header[] generateAuthHeader(String accessToken) {
        return new Header[] {
                new BasicHeader("Authorization", "Bearer " + accessToken)
        };
    }

    protected static Header[] generateJsonHeaders(String accessToken) {
        return new Header[] {
                new BasicHeader("Authorization", "Bearer " + accessToken),
                new BasicHeader("content-type", "application/json")
        };
    }

}
