package com.fri.http.rest.connections;

import com.fri.http.rest.response.YXJSONResponse;
import org.apache.http.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by zhangdahui on 2017/5/18.
 */
public class HttpClientPool {

    private static PoolingHttpClientConnectionManager cm;

    public static void initConnectionPool() {

        cm = new PoolingHttpClientConnectionManager();

        // Increase max total connection to 200
        cm.setMaxTotal(200);

        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);

        // Increase max connections for localhost:80 to 50
        HttpHost hostBaidu = new HttpHost("www.baidu.com", 80);
        cm.setMaxPerRoute(new HttpRoute(hostBaidu), 50);

        HttpHost hostKairosDB = new HttpHost("www.centos.org", 80);
        cm.setMaxPerRoute(new HttpRoute(hostKairosDB), 50);


    }

    ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {

        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {

            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));

            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();

                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {}
                }
            }

            HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);

            if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) {
                // Keep alive for 5 seconds only
                return 5 * 1000;
            } else {
                // otherwise keep alive for 30 seconds
                return 30 * 1000;
            }
        }

    };

    public static CloseableHttpClient getClient() {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        return httpClient;
    }

    public static YXJSONResponse getRequest(String url) {

        YXJSONResponse yxResp = new YXJSONResponse();

        CloseableHttpClient hc = HttpClientPool.getClient();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;

        String respStr = "got error data from [" + url + "]";
        try {
            response = hc.execute(httpget);
            HttpEntity et = response.getEntity();
            respStr = EntityUtils.toString(et);
            yxResp.ReturnCode = String.valueOf(response.getStatusLine().getStatusCode());
            yxResp.outPutSuccess(respStr);

        } catch (IOException e) {
            e.printStackTrace();
            yxResp.outPutError("IOERR", e.getMessage());
        } finally {
            return yxResp;
        }

    }

    public static YXJSONResponse postRequest(String url, String body) {

        YXJSONResponse yxResp = new YXJSONResponse();

        CloseableHttpClient hc = HttpClientPool.getClient();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;

        StringEntity se = new StringEntity(body, "UTF-8");

        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httpPost.setEntity(se);

        String respStr = "got error data from [" + url + "]";

        try {

            response = hc.execute(httpPost);
            System.out.println(response.getStatusLine().getStatusCode());
            HttpEntity et = response.getEntity();
            if(response.getEntity() != null){
                respStr = EntityUtils.toString(et);
                yxResp.outPutSuccess(respStr);
            }

        } catch (IOException e) {
            e.printStackTrace();
            yxResp.outPutError("IOERR", e.getMessage());
        } finally {
            return yxResp;
        }

    }


}
