package cn.reghao.autodop.dagent.machine;

import cn.reghao.autodop.common.machine.Machine;
import cn.reghao.autodop.common.mqtt.DefaultMqttClient;
import cn.reghao.autodop.common.msg.Message;
import cn.reghao.autodop.common.msg.MsgQueue;
import cn.reghao.autodop.common.msg.pub.PubMsg;
import cn.reghao.autodop.common.msg.pub.clazz.NodePubClazz;
import cn.reghao.autodop.common.util.thread.ThreadPoolWrapper;
import cn.reghao.jdkutil.serializer.JsonConverter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author reghao
 * @date 2021-09-03 09:22:42
 */
@Slf4j
public class NodeClazzPubImpl {
    private final ScheduledExecutorService scheduler;
    private final DefaultMqttClient mqttClient;
    private final Machine machine;
    private final String pubClazz;
    
    public NodeClazzPubImpl(DefaultMqttClient mqttClient, Machine machine) {
        this.scheduler = ThreadPoolWrapper.scheduledThreadPool("heartbeat", 1);
        this.mqttClient = mqttClient;
        this.machine = machine;
        this.pubClazz = NodePubClazz.class.getSimpleName();
    }
    
    public void nodeStart() {
        Machine.MachineDetail machineDetail = machine.detail();
        String jsonPayload = JsonConverter.objectToJson(machineDetail);
        PubMsg pubMsg = PubMsg.pubMsg(pubClazz, NodePubClazz.start.name(), jsonPayload);
        pub(pubMsg);
    }

    public void nodeShutdown() {
        ThreadPoolWrapper.shutdownScheduler(scheduler);
        Machine.MachineStat machineStat = machine.stat();
        String jsonPayload = JsonConverter.objectToJson(machineStat);
        PubMsg pubMsg = PubMsg.pubMsg(pubClazz, NodePubClazz.shutdown.name(), jsonPayload);
        pub(pubMsg);
    }

    public void nodeHeartbeat() {
        scheduler.scheduleAtFixedRate(new Heartbeat(), 3, 3, TimeUnit.SECONDS);
    }

    public void nodeLog() {
    }
    
    private void pub(PubMsg pubMsg) {
        Message message = Message.pubMessage(pubMsg);
        try {
            String topic = MsgQueue.dmasterTopic();
            mqttClient.pub(topic, 1, JsonConverter.objectToJson(message));
        } catch (MqttException e) {
            log.error("{}", e.getMessage());
        }
    }

    class Heartbeat implements Runnable {
        @Override
        public void run() {
            Machine.MachineStat machineStat = machine.stat();
            String jsonPayload = JsonConverter.objectToJson(machineStat);
            PubMsg pubMsg = PubMsg.pubMsg(pubClazz, NodePubClazz.heartbeat.name(), jsonPayload);
            pub(pubMsg);
        }
    }
}
