package net.northking.cctp.mobile.driver.websocket;


import com.alibaba.fastjson.JSON;
import net.northking.cctp.mobile.driver.entity.CmdAutomationResponse;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * todo:poc先这样整，后面优化细节
 */
public class AutomationSocketClient extends WebSocketClient {

    private String deviceId;

    public Semaphore semaphore;

    private CmdAutomationResponse response;

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

    public AutomationSocketClient(URI serverUri,String deviceId) {
        super(serverUri);
        this.deviceId = deviceId;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info("设备【{}】的自动化ws连接成功");
    }

    @Override
    public void onMessage(String s) {
        logger.debug("设备【{}】收到上位机执行结果回复：{}",deviceId,s);
        response = JSON.parseObject(s, CmdAutomationResponse.class);
        semaphore.release();//拿到结果
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.debug("设备【{}】自动化ws关闭，原因：{}",deviceId,s );
    }

    @Override
    public void onError(Exception e) {
        logger.debug("设备【{}】自动化ws出错，原因：",deviceId,e);
    }

    public CmdAutomationResponse getResponse() {
        return response;
    }

    public String getDeviceId() {
        return deviceId;
    }
}
