package vip.xiaonuo.coldchain.core.renke.config;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import rk.netDevice.sdk.p2.IDataListener;
import rk.netDevice.sdk.p2.RSServer;
import vip.xiaonuo.coldchain.core.renke.listener.JfcloudColdChainRenKeDefaultDataListener;
import vip.xiaonuo.coldchain.core.renke.util.IPUtil;
import vip.xiaonuo.coldchain.core.renke.util.ParamFileUtil;
import vip.xiaonuo.coldchain.core.service.dataprocess.handler.impl.RenKeColdChainDataHandler;
import vip.xiaonuo.coldchain.modular.monitordevice.service.MonitorDeviceService;

import javax.annotation.PreDestroy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Configuration
@EnableConfigurationProperties(JfcloudColdChainServerProperties.class)
@Slf4j
public class JfcloudColdChainServerAutoConfiguration {

    // 定义线程池用于异步启动 RSServer，避免阻塞主线程
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private RSServer rsServer;

    /**
     * 默认的数据监听器 Bean。如果用户没有自定义 IDataListener 实现，将会使用此默认实现。
     *
     * @return 默认的 IDataListener 实例
     */
    @Bean
    @ConditionalOnMissingBean
    public IDataListener defaultRkDataListener(RenKeColdChainDataHandler renKeColdChainDataHandler,
                                               @Autowired @Lazy MonitorDeviceService monitorDeviceService) {
        return new JfcloudColdChainRenKeDefaultDataListener(renKeColdChainDataHandler, monitorDeviceService);
    }


    /**
     * RSServer Bean 配置，使用异步方式启动，以避免阻塞应用启动。
     *
     * @param properties   RSServer 配置属性，包含端口等配置信息
     * @param dataListener 数据监听器，用于处理 RSServer 的各种数据回调
     * @return RSServer 实例
     */
    @Bean
    @ConditionalOnMissingBean
    @SneakyThrows
    public RSServer jfcloudColdChainServer(JfcloudColdChainServerProperties properties, IDataListener dataListener) {
        // 初始化 RSServer，并注入数据监听器
        String paramFilePath = ParamFileUtil.copyParamDatFileFromJarToCurrentDirectory();
        rsServer = RSServer.Initiate(properties.getPort(), paramFilePath);
        rsServer.addDataListener(dataListener);
        log.info("""
                ----------------------------------------------------------
                冷链通信服务(JfcloudColdChainServer)正在启动, Access URLs:
                访问地址:    tcp://{}:{}
                ----------------------------------------------------------
                """, IPUtil.getIp(), properties.getPort());
        // 异步启动 RSServer，避免阻塞主线程
        startJfcloudColdChainServerAsync(rsServer);
        return rsServer;
    }

    /**
     * 异步启动 RSServer，确保不会阻塞主线程。
     *
     * @param rsServer 要启动的 RSServer 实例
     */
    @Async("coldChainAsyncTask")
    public void startJfcloudColdChainServerAsync(RSServer rsServer) {
        executorService.submit(() -> {
            try {
                rsServer.start();
                log.info("RSServer 已成功启动");
            } catch (Exception e) {
                log.error("RSServer 启动失败", e);
            }
        });
    }

    /**
     * 关闭 RSServer，在 Spring 容器销毁时调用。
     */
    @PreDestroy
    public void shutdownJfcloudColdChainServer() {
        if (rsServer != null) {
            rsServer.stop();
            log.info("RSServer 已停止");
        }
        executorService.shutdown();
    }
}
