package net.northking.cctp.debuger.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;

public class WebClientListener extends Thread{

    private Session session;

    private Long prePingTime = System.currentTimeMillis();

    private boolean isConnected = true;

    private String sessionId;

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

    public WebClientListener(Session session,String sessionId){
        this.session = session;
        this.sessionId = sessionId;
    }

    @Override
    public void run() {
        while ((System.currentTimeMillis() - prePingTime < 60000) && isConnected) {
            try {
                Thread.sleep(45000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        if (isConnected) {
            logger.warn("sessionId:{},ping的心跳到期,准备断开与web的连接",this.sessionId);
            if (null != this.session) {
                try {
                    this.session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "长时间无法ping通，断开web端"));
                } catch (IOException e) {
                    logger.warn("sessionId:{}，对应的session关闭异常",this.sessionId,e);
                }
            }
        }
        logger.warn("sessionId:{},对应的ping监控线程退出。。。。。。。。。。",this.sessionId);
    }

    public void setPrePingTime(Long prePingTime){
        this.prePingTime = prePingTime;
    }

    public void exitWebWS(){
        this.isConnected = false;
    }

}
