package org.stm.api;

import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class HttpConnectionManager {


    private static final PoolingHttpClientConnectionManager connectionManager;
    private static final CloseableHttpClient httpClient;
    private static final IdleConnectionMonitorThread monitorThread;

    static {
        try {
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(SSLContext.getDefault());

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", factory)
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .build();

            connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            connectionManager.setMaxTotal(200);
            connectionManager.setDefaultMaxPerRoute(20);

            // 设置连接存活策略
            SocketConfig socketConfig = SocketConfig.custom()
                    .setSoTimeout(30000)
                    .build();
            connectionManager.setDefaultSocketConfig(socketConfig);

            // 设置连接闲置策略
            connectionManager.setValidateAfterInactivity(10000);

            // 设置请求配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setCookieSpec(CookieSpecs.STANDARD)
                    .setConnectTimeout(5000)
                    .setSocketTimeout(30000)
                    .setConnectionRequestTimeout(5000)
                    .build();

            // 创建一个单例的HttpClient
            httpClient = HttpClients.custom()
                    .setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(requestConfig)
                    .setConnectionManagerShared(true)
                    .build();

            // 启动一个守护线程来清理过期和闲置连接
            monitorThread = new IdleConnectionMonitorThread(connectionManager);
            monitorThread.setDaemon(true);
            monitorThread.start();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to initialize HttpConnectionManager", e);
        }
    }

    public static CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    /**
     * 关闭连接管理器和相关资源。
     * 应用程序在关闭时应该调用此方法。
     */
    public static void shutdown() {
        if (monitorThread != null) {
            monitorThread.shutdown();
        }

        try {
            if (httpClient != null) {
                httpClient.close();
            }
            if (connectionManager != null) {
                connectionManager.close();
            }
        } catch (IOException e) {
            // 记录日志但不抛出异常
            e.printStackTrace();
        }
    }

    // 注册JVM关闭钩子来关闭连接管理器
    static {
        Runtime.getRuntime().addShutdownHook(new Thread(HttpConnectionManager::shutdown));
    }

    // 闲置连接监控线程
    private static class IdleConnectionMonitorThread extends Thread {
        private final PoolingHttpClientConnectionManager connectionManager;
        private volatile boolean shutdown;

        public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connectionManager) {
            super("idle-connection-monitor");
            this.connectionManager = connectionManager;
        }

        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(5000);
                        // 关闭过期连接
                        connectionManager.closeExpiredConnections();
                        // 关闭空闲超过30秒的连接
                        connectionManager.closeIdleConnections(30, TimeUnit.SECONDS);
                    }
                }
            } catch (InterruptedException ex) {
                // 终止
            }
        }

        public void shutdown() {
            shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }
    }
}
