package net.northking.cctp.pc.driver.socket;

import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.pc.driver.constants.PCConstant;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.Semaphore;

/**
 * <p>Title: PCDriver</p>
 * <p>Description: </p>
 *
 * @Author chenjianfeng
 * @Version V1.0
 * @Date 2022/11/07
 * <p>Copyright: NorthKing@RPA（C）2020 版权</p>
 */
@Slf4j
public class PCDriver {

    /**
     * 许可证
     */
    public Semaphore semaphore = new Semaphore(0);

    /**
     * 返回码
     */
    public String resCode = null;

    /**
     * 返回结果
     */
    public String resResult;

    /**
     * 客户端
     */
    public WebSocketClient webSocketClient;


    public PCDriver(String address)  {
        try{
            if (webSocketClient != null && webSocketClient.isOpen()) {
                log.info("client is still open ...");
                return;
            }
            webSocketClient = new WebSocketClient(new URI(PCConstant.SOCKET_URI_PREFIX +
                    address + PCConstant.SOCKET_URI_SUFFIX), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("PC Engine Connect PC Robot Success ...");
                }

                @Override
                public void onMessage(String message) {
                    log.info("PC Engine Receive Message => " + message);
                    resResult = message;
                    semaphore.release();
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("close code -> {}, reason: -> {}", i, s);
                    log.info("PC Engine Socket Close ....");
                    resCode = s;
                    resResult = "";
                }

                @Override
                public void onError(Exception e) {
                    log.error("PC Engine Socket Connect Error ", e);
                    resResult = "";
                }
            };
            webSocketClient.connect();
        }catch (Exception e){
            throw new RuntimeException("创建PC设备连接异常", e);
        }
    }

    /**
     * 发送消息
     * @param message 消息
     */
    public void send(String message){
        if (webSocketClient.getReadyState() == ReadyState.CLOSING
                || webSocketClient.getReadyState() == ReadyState.CLOSED) {
            log.info("PC Engine Socket Closing Start Reconnect ... ");
            webSocketClient.reconnect();
            try {
                // 等待重连，暂定1秒
                // todo: 重连次数？
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("休眠异常", e);
            }
            log.info("PC Engine Socket Closing Start Reconnect End ");
        }
        webSocketClient.send(message);
    }
}
