package org.ts.ddcs.main;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.rocksdb.RocksDB;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import org.ts.ddcs.constant.NetPortStatusConstant;
import org.ts.ddcs.dataStream.DataStreamManageHolder;
import org.ts.ddcs.dataStream.DataStreamManager;
import org.ts.ddcs.datatemplate.DataTemplateManageHolder;
import org.ts.ddcs.datatemplate.DataTemplateManager;
import org.ts.ddcs.net.DataChannel;
import org.ts.ddcs.net.DataChannelHolder;
import org.ts.ddcs.rest.RestHttpClient;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


/**
 * 数据报文处理主类
 *
 * @author dylan
 */
@Component
@Slf4j
public class MainProcessor {

    private RocksDB rocksDb;

    @Value("${spring.application.name}")
    public String serverName;

    @Value("${tsywxt-config.template.path}")
    public String templatesDirPath;

    @Value("${tsywxt-config.template.templates}")
    public String templates;

    @Value("${tsywxt-config.nio.listener.tcp-port}")
    public String tcpPort;

    @Value("${tsywxt-config.nio.listener.udp-port}")
    public String udpPort;

    @Value("${tsywxt-config.rockdb-config.save-path}")
    public String rockdbSavePath;

    @Value("${tsywxt-config.serves.sw-url}")
    public String servesSwUrl;

    @Value("${tsywxt-config.serves.szy-url}")
    public String servesSzyUrl;

    @Resource
    private RestHttpClient restHttpClient;

    static {
        RocksDB.loadLibrary();
    }

    @PostConstruct
    public void init() {
        log.info("************************************* " + serverName + "  服务启动 *************************************");
        try {
            log.info("初始化ROCKDB{}", rockdbSavePath);
            this.rocksDb = RocksDB.open(rockdbSavePath);
            log.info("初始化报文模板配置模块");
            DataProcessorHolder.newInstance().dataProcess = this;
            DataTemplateManager dataTemplateManager = new DataTemplateManager();
            dataTemplateManager.init(templatesDirPath, templates);
            DataTemplateManageHolder.newInstance().dataTemplateManager = dataTemplateManager;
            log.info("初始化网络通道模块");
            DataChannel dataChannel = new DataChannel();
            if (null != tcpPort && tcpPort.length() > 0) {
                String[] ports = tcpPort.split(",");
                for (String set : ports) {
                    String[] sets = set.split("-");
                    String port = sets[0].trim().toLowerCase();
                    String active = sets[1].trim().toUpperCase();
                    if (NetPortStatusConstant.ON.equals(active)) {
                        log.info("启动TCP通道 端口： {} ", port);
                        dataChannel.addTcpChannel(Integer.parseInt(port));
                    }
                }
            }
            if (null != udpPort && udpPort.length() > 0) {
                String[] ports = udpPort.split(",");
                for (String set : ports) {
                    String[] sets = set.split("-");
                    String port = sets[0].trim().toLowerCase();
                    String active = sets[1].trim().toUpperCase();
                    if (NetPortStatusConstant.ON.equals(active)) {
                        log.info("启动UDP通道 端口： {}", port);
                        dataChannel.addUdpChannel(Integer.parseInt(port));
                    }
                }
            }
            DataChannelHolder.newInstance().dataChannel = dataChannel;
            log.info("初始化数据流处理模块");
            DataStreamManager dataStreamManager = new DataStreamManager();
            dataStreamManager.init(this.templates, this.rocksDb);
            DataStreamManageHolder.newInstance().dataStreamManager = dataStreamManager;
        } catch (Exception e) {
            log.error(e.getMessage());
//            String[] args = new String[]{"1","2"};
//            ConfigurableApplicationContext context = SpringApplication.run(DataCollectApplication.class, args);
//            context.close();

//            int exitCode = SpringApplication.exit(DataCollectApplication.configurableApplicationContext, new ExitCodeGenerator() {
//                @Override
//                public int getExitCode() {
//                    // no errors
//                    return 0;
//                }
//            });
//            System.exit(exitCode);
        } finally {
            log.info("************************************* " + serverName + " 服务已成功运行 *************************************");
        }
    }

    public void postSwData(JSONObject data) {
        this.restHttpClient.post(this.servesSwUrl, data);
    }

    public void postSzyData(JSONObject data) {
        this.restHttpClient.post(this.servesSzyUrl, data);
    }
}
