package net.northking.cctp.upperComputer.service.impl;

import net.northking.cctp.upperComputer.deviceManager.AndroidDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import net.northking.cctp.upperComputer.driver.adb.AdbDevice;
import net.northking.cctp.upperComputer.entity.PhoneEntity;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import net.northking.cctp.upperComputer.exception.ParamMistakeException;
import net.northking.cctp.upperComputer.service.DeviceConnectionService;
import net.northking.cctp.upperComputer.webSocket.entity.CmdRequest;
import net.northking.cctp.upperComputer.webSocket.thread.AndroidMessageHandlerThread;
import net.northking.cctp.upperComputer.webSocket.thread.IosMacMessageHandlerThread;
import net.northking.cctp.upperComputer.webSocket.thread.IosWindowsAndLinuxMessageHandlerThread;
import net.northking.cctp.upperComputer.webSocket.thread.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ConnectionServiceImpl implements DeviceConnectionService {

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

        /**
     * 消息处理map
     */
    private ConcurrentHashMap<String, MessageHandler> messageHandleMap = new ConcurrentHashMap<>();

    /**
     * 后端连接session管理
     */
    private ConcurrentHashMap<Session, String> wsSessionMap = new ConcurrentHashMap<>();


    @Override
    public boolean prepareEnvironment(String serial, String type, Session session) {
        wsSessionMap.put(session, serial);
        MessageHandler handleMessage = messageHandleMap.get(serial);
        if ("android".equals(type)) {
            AdbDevice currentDevice = AndroidDeviceManager.getInstance().getCurrentDevice(serial);
            if (null == currentDevice) {
                logger.warn("当前设备【{}】已经离线",serial);
                return false;
            }
            //消息处理线程
            if (null == handleMessage) {
                logger.info("android设备【{}】的消息处理线程不存在，新创建一个", serial);
                try {
                    handleMessage = new AndroidMessageHandlerThread(currentDevice, session);
                    handleMessage.startHandMessage();
                    messageHandleMap.put(serial, handleMessage);
                } catch (ParamMistakeException e) {
                    logger.error("手机[{}]初始化环境出错", serial, e);
                    return false;
                } catch (ExecuteException e) {
                    logger.error("手机[{}]初始化环境出错", serial, e);
                    return false;
                }
            } else {
                logger.info("android设备【{}】的消息处理线程已存在，无需创建", serial);
            }
            logger.info("手机[{}]初始化环境完成。。。。。。。", serial);
            return true;
        } else if ("ios".equals(type)) {
            PhoneEntity phoneEntity = IOSDeviceManager.getInstance().getPhoneEntity(serial);
            if (!phoneEntity.getStatus()) {
                logger.warn("当前设备【{}】不在线", phoneEntity.getUdid());
                return false;
            }
            //消息处理线程
            if (null == handleMessage) {
                logger.info("ios设备【{}】的消息处理线程不存在，新创建一个", serial);
                boolean isMac = UpperComputerManager.getInstance().isMac();
                if (isMac) {
                    logger.debug("设备【{}】接到mac上位机上.............",phoneEntity.getUdid());
                    try {
                        handleMessage = new IosMacMessageHandlerThread(phoneEntity, session);
                    } catch (Exception e) {
                        logger.error("手机[{}]初始化环境出错", serial, e);
                        return false;
                    }
                } else {
                    logger.debug("设备【{}】接到window或linux上位机上.............");
                    try {
                        handleMessage = new IosWindowsAndLinuxMessageHandlerThread(phoneEntity, session);
                    } catch (Exception e) {
                        logger.error("手机[{}]初始化环境出错", serial, e);
                        return false;
                    }
                }
                handleMessage.startHandMessage();
                messageHandleMap.put(phoneEntity.getUdid(), handleMessage);
            } else {
                logger.info("ios设备【{}】的消息处理线程已存在，无需创建", serial);
            }
            logger.info("手机[{}]初始化环境完成。。。。。。。", serial);
            return true;
        } else {
            logger.info("手机[{}]平台不正确，选择的平台为：{}。。。。。。。", serial,type);
            return false;
        }
    }

    @Override
    public void handleMessage(String type, CmdRequest request) {
        messageHandleMap.get(request.getSerial()).addQueue(request);
    }

    @Override
    public void closeDeviceSession(Session session) {
        if (null != session) {
            String serial = wsSessionMap.remove(session);
            if (StringUtils.hasText(serial)) {
                logger.warn("设备【{}】连接断开", serial);
                MessageHandler messageHandler = messageHandleMap.remove(serial);
                if (null != messageHandler) {
                    messageHandler.stopAndExit();
                }
            }
        }
    }

    @Override
    public MessageHandler getHandleMessageThread(String serial) {
        return messageHandleMap.get(serial);
    }

    @Override
    public void closeConnectedDevice() {
        for (String serial : messageHandleMap.keySet()) {
            logger.warn("关闭设备【{}】的连接",serial);
            MessageHandler messageHandler = messageHandleMap.get(serial);
            messageHandler.stopAndExit();
        }
        messageHandleMap.clear();
    }

    @Override
    public void deviceAgentDead(String serial) {
        MessageHandler messageHandler = messageHandleMap.get(serial);

        if (null != messageHandler) {
            messageHandler.clearAndCloseDeviceAgentConnection();
//            if ("android".equals(type)) {
//                AndroidMessageHandlerThread androidMessageHandlerThread = (AndroidMessageHandlerThread) messageHandler;
//                if (androidMessageHandlerThread.isAlive() && !androidMessageHandlerThread.isInterrupted()) {
//                    androidMessageHandlerThread.clearAndCloseDeviceAgentConnection();
//                }
//            } else {
//                AbstractIosMessageHandlerThread iosMessageHandler = (AbstractIosMessageHandlerThread) messageHandler;
//                if (iosMessageHandler.isAlive() && !iosMessageHandler.isInterrupted()) {
//                    iosMessageHandler.clearAndCloseDeviceAgentConnection();
//                }
//            }
        }
    }

    @Override
    public void deviceAgentAlready(String serial) {
        MessageHandler messageHandler = messageHandleMap.get(serial);
        if (null != messageHandler) {
            messageHandler.reConnectDeviceAgent();
        }
    }
}
