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

import net.northking.cctp.upperComputer.constants.ResponseCmd;
import net.northking.cctp.upperComputer.utils.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : yineng.huang
 * @date : 2024/6/19 18:21
 */
public class NotifyWebCloseConnectionThread extends Thread {

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

    private boolean notify = true;

    private Session webSession;

    private String serial;

    public NotifyWebCloseConnectionThread(Session webSession, String serial) {
        this.webSession = webSession;
        this.serial = serial;
        setName(serial + "]关闭前端连接");
    }

    @Override
    public void run() {
        try {
            logger.debug("等待设备【{}】上线中.............................", serial);
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            logger.warn("设备【{}】上线了，不通知前端断开了.....", serial);
            interrupt();
            notify = false;
        }
        if (notify) {
            logger.warn("设备【{}】等了很久都没上线，通知前端断开.....", serial);
            //通知前端设备现在处于掉线的状态,前端开始转圈
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put(ResponseCmd.DeviceStatus.STATUS, ResponseCmd.DeviceStatus.DISCONNECT);
            messageMap.put(ResponseCmd.DeviceStatus.MESSAGE, "设备掉线");
            SessionUtils.sendMessageInitiative(webSession, ResponseCmd.DEVICE_STATUS, serial, messageMap, "设备掉线了");
        } else {
            logger.warn("设备【{}】又上线了.....", serial);
        }
    }

    public void cancelNotifyWebDisconnect() {
        this.notify = false;
        interrupt();
    }
}
