package com.tofly.feesapi.file.fileconfiguration;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class FTPClientPoolManager {

    @Autowired
    private FTPFileStorageProperties fileStorageProperties;

    private static FTPFileStorageProperties staticConfig;

    private static GenericObjectPool<FTPClient> pool;

    @PostConstruct
    public void initStatic() throws Exception {
        staticConfig = fileStorageProperties;
        initPool();
    }

    // 初始化连接池（静态代码块或启动时调用）
    public static void initPool() {
        // 1. 配置连接池参数
        GenericObjectPoolConfig<FTPClient> config = new GenericObjectPoolConfig<>();
        config.setMaxTotal(500);          // 最大连接数
        config.setMaxIdle(100);           // 最大空闲连接
        config.setMinIdle(50);            // 最小空闲连接
        config.setTestOnBorrow(false);    // 借用时验证连接
        config.setTestWhileIdle(true);   // 空闲时定期检测
        config.setTimeBetweenEvictionRunsMillis(10000);  // 空闲检测周期10秒
        config.setMinEvictableIdleTimeMillis(250000);//空闲对象的最小存活时间，超过此时间可能被回收 60秒
        config.setSoftMinEvictableIdleTimeMillis(300000);//空闲对象被回收前的存活时间（需满足 minIdle 限制）。
        config.setBlockWhenExhausted(true);  // 连接耗尽时阻塞等待
        config.setMaxWaitMillis(20000);       // 等待超时20秒

        // 2. 初始化连接池
        PooledFTPClientFactory factory = new PooledFTPClientFactory(
                staticConfig.getServer(),
                staticConfig.getPort(),
                staticConfig.getUserName(),
                staticConfig.getPassword()
        );
        pool = new GenericObjectPool<>(factory, config);
    }

    // 获取连接
    public static FTPClient borrowClient() throws Exception {
        return pool.borrowObject();
    }

    // 归还连接
    public static void returnClient(FTPClient ftpClient) {
        if (ftpClient != null) {
            pool.returnObject(ftpClient);
        }
    }

    // 废弃异常连接
    public static void invalidateClient(FTPClient ftpClient) throws Exception {
        if (ftpClient != null) {
            pool.invalidateObject(ftpClient);
        }
    }
}
