package net.northking.cctp.mobile.config;

import net.northking.cctp.mobile.db.impl.MobileConnectServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ConnectThreadPoolService {

    private static final Logger logger = LoggerFactory.getLogger(MobileConnectServiceImpl.class);

    @Autowired
    private MobileConnectionConfig mobileConnectionConfig;

    @Bean
    public ThreadPoolExecutor createThreadPoolExecutor(){
        String size = mobileConnectionConfig.getEnableSize();
        int enableConnectSize = 4;
        if (StringUtils.hasText(size)) {
            try {
               enableConnectSize = Integer.parseInt(size);
            } catch (NumberFormatException e) {
                logger.debug("配置中nk.mobile-connection.connect-pool.enable-size的值格式不对：{}", size, e);
            }
        } else {
            logger.debug("未配置中nk.mobile-connection.connect-pool.enable-size最大连接数,采取默认连接数");
        }
        logger.debug("单个服务最大手机连接数为：{}",enableConnectSize);
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(enableConnectSize, enableConnectSize, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>(), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("connect-mobile-pool-"+thread.getName());
                return thread;
            }
        },new ThreadPoolExecutor.AbortPolicy());
        logger.info("手机连接线程池初始化完毕.....................................");
        return executorService;
    }

}
