package net.northking.cctp.debuger.websocket;


import net.northking.cctp.debuger.service.InterfaceScriptDebugService;
import net.northking.cctp.debuger.service.MobileScriptDebugService;
import net.northking.cctp.debuger.util.SpringUtils;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

import java.util.concurrent.TimeUnit;


public class WebSocketClientChannel extends WebSocketClient{
    private static final Logger logger = LoggerFactory.getLogger(WebSocketClientChannel.class);

    private String sessionId;

    private String requestId;

    private final  MessageHandler messageHandler;
    public WebSocketClientChannel(URI serverUri, MessageHandler handler, String sessionId) {
        super(serverUri);
        this.messageHandler = handler;
        this.sessionId = sessionId;
    }

    public WebSocketClientChannel(URI serverUri, MessageHandler handler, String sessionId,String requestId) {
        super(serverUri);
        this.messageHandler = handler;
        this.sessionId = sessionId;
        this.requestId = requestId;
    }

    public boolean isConnected() {
        int chkTimes = 0;
        while(!this.getReadyState().equals(ReadyState.OPEN) && chkTimes++<3 ){
            logger.info("Connecting ...");
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (Exception e){
                logger.error("Error",e);
            }
        }
        return this.getReadyState().equals(ReadyState.OPEN);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info("Receive ws server handershake:{}",serverHandshake.getContent());
        logger.info("localAddr:{}",getLocalSocketAddress());
    }

    @Override
    public void onMessage(String msg) {
        logger.debug("Receive a msg:{}",msg);
        messageHandler.handle(msg);
    }

    @Override
    public void send(String text) {
        logger.info("Send a msg to engine:{}",text);
        super.send(text);
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.warn("服务与引擎的ws断开，断开原因：{}",s);
        //引擎断开，移除ws客户端
        SpringUtils.getBean(MobileScriptDebugService.class).removeEngineSession(this.sessionId);
        SpringUtils.getBean(InterfaceScriptDebugService.class).removeEngineSession(this.sessionId,this.requestId);
    }

    @Override
    public void onError(Exception e) {
        logger.warn("服务与引擎的ws连接错误，原因：",e);
        //引擎连接错误，移除ws客户端
        SpringUtils.getBean(MobileScriptDebugService.class).removeEngineSession(this.sessionId);
        SpringUtils.getBean(InterfaceScriptDebugService.class).removeEngineSession(this.sessionId,this.requestId);
    }

}
