package net.northking.cctp.se.lifecycle;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.se.dto.ScriptEngineInfo;
import net.northking.cctp.se.lifecycle.constant.MQConstant;
import net.northking.cctp.se.lifecycle.entity.HeartbeatInfoDto;
import net.northking.cctp.se.thread.ExecutorPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * 异步等待任务清空掉起关闭服务进程
 */
public class StopServerThread extends Thread{
    private static final Logger logger = LoggerFactory.getLogger(LifecycleSchedule.class);

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final RabbitTemplate rabbitTemplate;

    private boolean enforce = false;

    StopServerThread(RestTemplate restTemplate,ObjectMapper objectMapper,RabbitTemplate rabbitTemplate, boolean enforce){
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.enforce = enforce;
    }

    public void run(){
        //等待现有线程池任务全部清空
        boolean flag =true;
        while(flag){
            //pcui线程
            boolean pcui = ExecutorPool.getPCPool().getActiveCount() == 0;
            //mobile线程池
            boolean mob = ExecutorPool.getMobilePool().getActiveCount() == 0;
            //interface线程池
            boolean inter = ExecutorPool.getApiPool().getActiveCount() == 0;
            if(this.enforce || (pcui && mob && inter)){
                flag=false;
                logger.info("检查到没有运行的任务，关闭服务。");
            }else{
                logger.info("引擎等待关闭，等待任务完成：pcui任务数：{} ，移动任务数：{}，接口任务数：{}",
                        ExecutorPool.getPCPool().getActiveCount(),
                        ExecutorPool.getMobilePool().getActiveCount(),
                        ExecutorPool.getApiPool().getActiveCount()
                );
                try {
                    // 每5秒钟查看任务情况
                    Thread.sleep(5L*1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logger.error("休眠异常", e);
                }
            }
        }
        //
        // 关闭前发送心跳
        EngineRuntime engineRuntime = EngineRuntime.getRuntime();
        ScriptEngineInfo engineInfo = engineRuntime.getEngineInfo();
        HeartbeatInfoDto dto = new HeartbeatInfoDto();
        dto.setEngineId(engineInfo.getEngineId());
        dto.setEngineVersion(engineInfo.getVersion());
        dto.setEngineStatus("3");
        deployNotice(dto);
        //服务停止
        logger.info("停止服务准备已完成 服务关闭 ----------");

        System.exit(0);
    }

    private void deployNotice(Object object) {
        byte[] json;
        try{
            json = objectMapper.writeValueAsBytes(object);
            MessageBuilder mb = MessageBuilder.withBody(json);
            mb.setContentType(MediaType.APPLICATION_JSON_VALUE);
            rabbitTemplate.send(MQConstant.ENGINE_HEARTBEAT,mb.build());
        }catch (Exception e){
            logger.info("mq消息解析失败："+e.getMessage());
        }
    }
}
