package net.northking.cctp.mobile.thread;

import net.northking.cctp.common.security.authentication.NKSecurityContext;
import net.northking.cctp.mobile.constants.MobileConnectionConstants;
import net.northking.cctp.mobile.db.service.MobileConnectService;
import net.northking.cctp.mobile.dto.device.CdDeviceCtrl;
import net.northking.cctp.mobile.dto.device.CdMobileDevice;
import net.northking.cctp.mobile.dto.device.DeviceInfoDto;
import net.northking.cctp.mobile.entity.UpperWSRequest;
import net.northking.cctp.mobile.entity.WSRequest;
import net.northking.cctp.mobile.entity.WSResponse;
import net.northking.cctp.mobile.exception.MobileConnectException;
import net.northking.cctp.mobile.feign.device.DeviceMgrFeignClient;
import net.northking.cctp.mobile.socket.UpperWebSocketClient;
import net.northking.cctp.mobile.util.JsonUtils;
import net.northking.cctp.mobile.util.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ProcessMsgThread extends Thread{

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

    private String deviceId;

    private String deviceToken;

    private String userToken;

    private String sessionId;

    private String mode;

    private Session webSession;

    private final String USE_DEVICE_PATH = "/api/cctp-device-mgr/v1/device/mobile/achieve/%s";

    private final String USE_DEVICE_PATH_BATCH = "/api/cctp-device-mgr/v1/device/group/control";

    private final String TEMPLATE_UPPER_WS_URI = "ws://%s:%s/connectMobile?serial=%s&type=%s";

    private BlockingQueue<WSRequest> msgQueue = new LinkedBlockingQueue();

    private UpperWebSocketClient upperSocketClient;

    public ProcessMsgThread(String userToken, Session session, String sessionId, String deviceId, String deviceToken, String mode){
        this.userToken = userToken;
        this.sessionId = sessionId;
        this.deviceId = deviceId;
        this.deviceToken = deviceToken;
        this.webSession = session;
        this.mode = mode;
        setName(deviceId+"]-web-msg");
    }

    @Override
    public void run() {
        logger.debug("processMsgThread is running...");
        WSRequest msgRequest = null;
        while (!isInterrupted()) {
            try {
                msgRequest = msgQueue.take();
            } catch (InterruptedException e) {
                interrupt();
                logger.error("获取前端请求信息异常导致线程中断：", e);
                break;
            }
            logger.debug("processMsgThread msgRequest => {}", JsonUtils.toJson(msgRequest));
            String cmd = msgRequest.getCmd();
            logger.debug("cmd:{}",cmd);
            switch (cmd) {
                case MobileConnectionConstants.CommandConstants.CMD_SCREEN_ON:
                    handleScreenOn(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_SCREEN_SIZE:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_SCREEN_QUALITY:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_TOUCHDOWN:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_TOUCHMOVE:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_TOUCHUP:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_KEYPRESS:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_KEYDOWN:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_KEYUP:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_TYPE:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_INPUT_SETTEXT:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_CLIPBOARD_PAST:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_CLIPBOARD_COPY:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_DEVICE_START_NODE:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_DEVICE_STOP_NODE:
                    handleMessageForward(msgRequest);
                    break;
                case MobileConnectionConstants.CommandConstants.CMD_DEVICE_EXIT:
                    exitMobile();
                    break;
                default:
                    logger.warn("指令不符合要求");
                    break;
            }
        }
    }


    private void exitMobile(){
        if (StringUtils.hasText(deviceToken)) {
            if (StringUtils.isNotBlank(mode)) {
                logger.info("设备【{}】是直播退出，不释放手机.......",deviceId);
            } else {
                SpringUtils.getBean(MobileConnectService.class).releaseUsingDevice(deviceId, deviceToken);
            }
            //校验是否已经正常释放设备完成报告
            deviceToken = null;
        } else {
            logger.info("设备【{}】已经释放.......",deviceId);
        }
        deviceId = null;
    }

    public void addMsg(WSRequest msg){
        msgQueue.add(msg);
        logger.info("前端设备连接信息添加进队列");
    }

    public void exit() {
        this.alive = false;
    }

    private void sendMsg2Web(String deviceId, String msg){
        if(null == webSession || !webSession.isOpen()){
            logger.warn("前端Session[deviceId:{}]已关闭",deviceId);
            return;
        }
        try{
            synchronized (webSession){
                if (webSession.isOpen()) {
                    webSession.getBasicRemote().sendText(msg);
                }else {
                    logger.warn("前端会话已关闭无法发送msg: "+msg);
                }
            }
        }catch (Exception e){
            logger.error(String.format("Error when responsing to deviceId:%s",deviceId),e);
            //增加重发机制
        }
    }

    private void handleScreenOn(WSRequest request) {
        WSResponse response = null;
        if (!StringUtils.hasText(deviceToken)) {
            response = WSResponse.buildResponse(request, true, false, "设备token不能为空");
            sendMsg2Web(deviceId, JsonUtils.toJson(response));
            return;
        }
        try {
            connect2Upper();
        } catch (Exception e) {
            logger.warn("连接上位机异常", e);
            if (e instanceof MobileConnectException) {
                response = WSResponse.buildResponse(request, true, false, e.getMessage());
            } else {
                response = WSResponse.buildResponse(request, true, false, "上位机连接失败，请稍后再试");
            }
            sendMsg2Web(deviceId, JsonUtils.toJson(response));
            return;
        }
        sendMsg2Upper(request);
    }

    /**
     * 连接上位机
     */
    private boolean connect2Upper() throws Exception {
        if (null == upperSocketClient || !upperSocketClient.isConnected()) {
            logger.debug("上位机连接为空......，获取上位机ip地址");
            String upperUri = getUpperUrl(deviceToken);
            if (null == upperUri) {
                throw new MobileConnectException("未查到手机所在的上位机地址");
            }
            logger.debug("开始连接上位机,deviceId:{},upperUri:{}", deviceId, upperUri);
            upperSocketClient = new UpperWebSocketClient(new URI(upperUri),webSession,deviceId,sessionId);
            try {
                upperSocketClient.connect();
            } catch (Exception e) {
                logger.error("上位机连接异常：", e);
                throw new MobileConnectException("上位机连接异常");
            }
            if (upperSocketClient.isConnected()) {
                logger.info("设备【{}】上位机连接成功。", deviceId);
                return true;
            } else {
                logger.info("设备【{}】上位机连接失败。");
                throw new MobileConnectException("连接上位机超时");
            }
        } else {
            logger.info("手机【{}】后台与上位机的链接还存在，直接用", deviceId);
            return true;
        }

    }

    /**
     * 根据设备token获取上位机ip和端口
     *
     * @param deviceToken
     * @return
     */
    private String getUpperUrl(String deviceToken) {
        ResultWrapper<DeviceInfoDto> wrapper = null;
        String urlInfo = null;
        try {
            wrapper = SpringUtils.getBean(DeviceMgrFeignClient.class).getDeviceInfoByToken(deviceToken);
            logger.debug("获取到设备信息：{}", JsonUtils.toJson(wrapper));
            if (wrapper.isSuccess() && null != wrapper.getData()) {
                CdDeviceCtrl deviceCtrl = wrapper.getData().getCdDeviceCtrl();
                CdMobileDevice mobileDevice = wrapper.getData().getCdMobileDevice();
                if (null != deviceCtrl && null != mobileDevice) {
                    String ctrlIp = deviceCtrl.getCtrlIp();
                    String ctrlPort = deviceCtrl.getCtrlPort();
                    String serial = mobileDevice.getId();
                    String platform = mobileDevice.getPlatform();
                    if (StringUtils.hasText(ctrlIp) && StringUtils.hasText(ctrlPort) && StringUtils.hasText(serial) && StringUtils.hasText(platform)) {
                        String plat = "0".equals(platform) ? "android" : "ios";
                        urlInfo = String.format(TEMPLATE_UPPER_WS_URI, ctrlIp, ctrlPort, serial, plat);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("根据设备token获取设备信息异常", e);
        }
        return urlInfo;
    }

    /**
     * 转发消息
     * @param msgRequest
     */
    private void handleMessageForward(WSRequest msgRequest) {
        sendMsg2Upper(msgRequest);
    }

    /**
     * 发送消息到上位机
     * @param request
     */
    private void sendMsg2Upper(WSRequest request){
        String sessionId = request.getSessionId();
        WSResponse response = null;
        if (null == upperSocketClient){
            logger.warn("上位机会话为空，deviceId：{}",deviceId);
            //先给前端再发送最后一次的屏幕流
//            sendLastStream2Web(deviceId);
            logger.info("尝试连接...");
            //todo:这里传状态
            response = WSResponse.newResponse()
                    .cmd(MobileConnectionConstants.CommandConstants.CMD_DEVICE_STATUS)
                    .sessionId(sessionId);
            try{
                response.withData(MobileConnectionConstants.ReplyConst.KEY_DEVICE_STATUS_TYPE,MobileConnectionConstants.ReplyConst.VAL_DEVICE_STATUS_CONNECTING);
                sendMsg2Web(deviceId,JsonUtils.toJson(response));
                int times = 0 ;
                while (upperSocketClient==null && times++ <3 ){
                    connect2Upper();
                }
                if (upperSocketClient!=null){
                    response.withData(MobileConnectionConstants.ReplyConst.KEY_DEVICE_STATUS_TYPE,MobileConnectionConstants.ReplyConst.VAL_DEVICE_STATUS_CONNECTED);
                }else {
                    response.withData(MobileConnectionConstants.ReplyConst.KEY_DEVICE_STATUS_TYPE,MobileConnectionConstants.ReplyConst.VAL_DEVICE_STATUS_DISCONNECTED);
                }
            }catch (Exception e){
                logger.error("连接上位机异常",e);
                response.withData(MobileConnectionConstants.ReplyConst.KEY_DEVICE_STATUS_TYPE,MobileConnectionConstants.ReplyConst.VAL_DEVICE_STATUS_DISCONNECTED);
            }finally {
                sendMsg2Web(deviceId,JsonUtils.toJson(response));
            }
        }
        if (null != upperSocketClient){
            UpperWSRequest upperWSRequest = UpperWSRequest.newRequest().cmd(request.getCmd())
                    .serial(deviceId)
                    .requestId(request.getRequestId())
                    .withData(request.getData());
            upperSocketClient.send(JsonUtils.toJson(upperWSRequest));
        }else{
            logger.warn("服务端转发上位机消息失败:[sessionId:{},cmd:{}]",sessionId,request.getCmd());
            //todo:通知前端连不上上位机
            response = WSResponse.newResponse()
                    .cmd(MobileConnectionConstants.CommandConstants.CMD_DEVICE_STATUS)
                    .sessionId(sessionId);
            sendMsg2Web(deviceId,JsonUtils.toJson(response));
        }
    }

    public void cleanDataInExit() {
        msgQueue.clear();
        interrupt();
        if (null != upperSocketClient && upperSocketClient.isConnected()) {
            upperSocketClient.closeUpperConnection();
        }
        exitMobile();
    }
}
