package net.northking.cctp.se.device.bean;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.element.core.DeviceDriver;
import net.northking.cctp.pc.driver.dto.EngineResultDto;
import net.northking.cctp.pc.driver.socket.PCDriver;

import javax.websocket.CloseReason;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

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

    public static final int DEFAULT_TIMEOUT = 31;

    public PCDeviceDriver(String address) {
        super(address);
    }

    @SneakyThrows
    @Override
    public void destroy() {
        log.info(" PC driver destroyed ... ");
        Map<String, Object> completeMap = new HashMap<>(2);
        String cmd = "Complete";
        completeMap.put("cmd", cmd);
        completeMap.put("seqId", IdUtil.simpleUUID());
        // 发送webSocket消息至PC执行机
        log.info("pc complete send => " + JSONUtil.toJsonStr(completeMap));
        try {
            this.send(JSONUtil.toJsonStr(completeMap));
            if (!this.semaphore.tryAcquire(DEFAULT_TIMEOUT, TimeUnit.SECONDS)) {
                throw new RuntimeException("指令[" + cmd + "]执行超时");
            }
            if (StrUtil.isBlank(this.resResult)) {
                throw new RuntimeException("指令[" + cmd + "]执行结果为空");
            }
            EngineResultDto engineResult = JSONUtil.toBean(this.resResult, EngineResultDto.class);
            if (!engineResult.getState().equals(0)){
                throw new RuntimeException(engineResult.getMsg());
            }
            log.info("clear execute env result => " + JSONUtil.toJsonStr(engineResult));
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        log.info("clean script execute env success .... ");
        // 关闭和机器人的连接
        this.webSocketClient.close(CloseReason.CloseCodes.NORMAL_CLOSURE.getCode(), "关闭与机器人的连接");
    }

    //这两个是手机端使用的，PC不需要实现
    @Override
    public void setFuture(Future future) {

    }

    @Override
    public Future getFuture() {
        return null;
    }
}
