package net.northking.cctp.upperComputer.init;


import net.northking.cctp.upperComputer.deviceManager.AndroidDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 上位机启动完成时，初始化：包括初始化
 */
@Component
public class UpperComputerInit implements ApplicationRunner, ApplicationListener<WebServerInitializedEvent> {

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

    private int port;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //0.初始化上位机
        logger.info("0.准备初始化上位机参数...................");
        UpperComputerManager.getInstance().setPort(port);
        UpperComputerManager.getInstance().initUpperComputerParam();
        logger.info("1.初始化上位机参数完成...................");

        //1.开始注册
        UpperComputerManager.register();
        logger.info("2.上位机注册完成...................");

        //2.发送上位机心跳
        logger.info("3.开启上位机心跳。。。。。。。。。。。。。。。。");
        UpperComputerManager.sendHeartToServer();

        //3.注册专属队列
        UpperComputerManager.registerQueue();
        logger.info("4.上位机专属队列绑定完成....................");

        //4.初始化ios设备
        logger.info("5.开启ios设备监听。。。。。。。。。。。");
        IOSDeviceManager.getInstance().start();

        if (!UpperComputerManager.getInstance().getOperatingSystem().startsWith("Mac")) {  //mac上面暂时不考虑接android
            //5.开启android设备监听
            logger.info("6.开始启动android设备监控。。。。。。");
            AndroidDeviceManager.getInstance().start();
        }
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        //获取程序实际端口
        port = webServerInitializedEvent.getWebServer().getPort();
        logger.info("上位机启动端口：{}",port);
    }
}
