package net.northking.cctp.upperComputer.deviceManager.thread;

import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.driver.ios.NKAgent;
import net.northking.cctp.upperComputer.driver.usbmuxd.AppleDevice;
import net.northking.cctp.upperComputer.entity.PhoneEntity;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.LinkedHashMap;

/**
 * @author : yineng.huang
 * @date : 2023/10/16 14:42
 */
public abstract class IosDeviceInitThread extends Thread {
    private final static Logger logger = LoggerFactory.getLogger(IosDeviceInitThread.class);

    protected PhoneEntity phone;

    protected LinkedHashMap<String, Object> deviceInfo;

    protected NKAgent nkAgent;

    protected AppleDevice appleDevice;

    public IosDeviceInitThread(PhoneEntity phone, AppleDevice appleDevice) {
        this.phone = phone;
        this.appleDevice = appleDevice;
        setName("【" + phone.getUdid() + "】初始化线程");
    }


    protected void createNKAgent() {
        nkAgent = new NKAgent(this.appleDevice);
        boolean nkAgentReady = false;
        int reTryTime = 1;
        do {
            logger.debug("尝试第{}次连接设备【{}】的nkAgent", reTryTime, phone.getUdid());
            try {
                nkAgent.connect();
                nkAgentReady = nkAgent.getStatus();
                logger.debug("设备【{}】的nkAgent连接完成，结果：{}", phone.getUdid(),nkAgentReady);
                if (nkAgentReady) {
                    logger.debug("设置设备【{}】的帧数为：{}", phone.getUdid(), 25);
                    nkAgent.setMJPEGServerRate(25);
                } else {
                    logger.error("第{}次连接设备【{}】的agent不成功，等待下一次......",reTryTime, phone.getUdid());
                }
            } catch (IOException e) {
                logger.error("第{}次连接设备【{}】的agent出错",reTryTime, phone.getUdid(), e);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                    break;
                }
            }
            reTryTime++;
        } while (!nkAgentReady && reTryTime <= 5);
        if (!nkAgentReady) {
            throw new ExecuteException(String.format("无法创建设备【%s】nkAgent", phone.getUdid()));
        }
        logger.debug("设置设备【{}】的nkAgent掉线之后的监听器................", phone.getUdid());
        nkAgent.setOnDisconnectListener(() -> {
            logger.warn("设备【{}】的nkAgent失效了，需要重新创建...........", phone.getUdid());
            IOSDeviceManager.getInstance().getIosInitThread(phone.getUdid()).createNKAgent();
            logger.warn("设备【{}】的nkAgent重新创建完成...........", phone.getUdid());
        });
        logger.debug("设备【{}】的nkAgent连接完毕................", phone.getUdid());
    }

    public NKAgent getNkAgent() {
        return nkAgent;
    }

    public abstract LinkedHashMap<String, Object> getDeviceInfo() throws IOException;

    public abstract void exitWdaAndProxy();


}
