package net.northking.cctp.upperComputer.deviceManager.thread;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.northking.cctp.upperComputer.constants.UpperComputerConstant;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

public class UpperComputerHeartThread extends Thread{

    private boolean isAlive = true;

    private Logger logger = LoggerFactory.getLogger(UpperComputerHeartThread.class);

    private RabbitTemplate rabbitTemplate;

    private ObjectMapper objectMapper;

    public UpperComputerHeartThread() {
        this.rabbitTemplate = SpringUtil.getBean(RabbitTemplate.class);
        this.objectMapper = SpringUtil.getBean(ObjectMapper.class);
        setName("上位机心跳线程");
    }

    @Override
    public void run() {
        while (!isInterrupted() && isAlive) {
            try {
                logger.debug("上位机程序设置上位机心跳，时间：{},内容：{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), JSON.toJSONString(UpperComputerManager.getInstance().getComputerHeartInfo()));
                Message message = new Message(objectMapper.writeValueAsBytes(UpperComputerManager.getInstance().getComputerHeartInfo()), new MessageProperties());
                rabbitTemplate.send(UpperComputerConstant.HEART_MQ_EXCHANGE_NAME, "", message);
                Thread.sleep(20000);
            } catch (Exception e) {
                logger.error("上位机发送心跳报错了。。。。。。。", e);
            }
        }
        logger.warn("上位机的心跳线程停止。。。。。。。。。");
    }


    public void kill(){
        logger.warn("即将停止上位机的心跳线程。。。。。。");
        this.isAlive = false;
        interrupt();
    }

}
