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

import net.northking.cctp.mobile.driver.websocket.AutomationSocketClient;
import org.java_websocket.enums.ReadyState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;


public class MobileDriver {

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

    private AutomationSocketClient socketClient;

    private String deviceId;

    private String type;

    public String getDeviceId() {
        return deviceId;
    }

    private String urlTemplate = "ws://%s/automation?type=%s&serial=%s";

    public MobileDriver(String upperUrl, String deviceId, String type) throws URISyntaxException {
        this.deviceId = deviceId;
        this.type = type;
        String connectUrl = String.format(urlTemplate, upperUrl, type, deviceId);
        logger.info("设备【{}】自动化ws驱动连接地址：{},类型：{}", deviceId, connectUrl,type);
        URI uri = new URI(connectUrl);
        socketClient = new AutomationSocketClient(uri, deviceId);
        socketClient.connect();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            logger.warn("取消设备【{}】的driver创建",e);
            return;
        }
        if (socketClient.isOpen()) {
            logger.info("设备【{}】已连接自动化ws到上位机", deviceId);
        } else {
            throw new RuntimeException("创建驱动失败");
        }
    }

    public void destroyDriver() {
        if (null != socketClient) {
            socketClient.close();
        }
        logger.warn("设备【{}】的driver关闭完成............", deviceId);
    }

    public void send(String message) {
        if (socketClient.getReadyState() == ReadyState.CLOSING
                || socketClient.getReadyState() == ReadyState.CLOSED) {
            logger.info("设备【{}】的引擎到上位机的ws连接关闭，重新连接............", deviceId);
            socketClient.reconnect();
            try {
                // 等待重连，暂定1秒
                // todo: 重连次数？
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                logger.error("休眠异常", e);
            }
            logger.info("设备【{}】的引擎到上位机的ws连接完成............", deviceId);
        }
        socketClient.send(message);
    }

    public AutomationSocketClient getSocketClient() {
        return socketClient;
    }

}
