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.Calendar;
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;

    /**
     * wda进程信息
     */
    protected Process process;

    protected boolean isFBServerReady = false;


    private int frame = 12;

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


    protected synchronized void createNKAgent(String tag) {
        logger.debug("createNKAgent:{}",tag);
        nkAgent = new NKAgent(this.appleDevice);
        nkAgent.setOnDisconnectListener(() -> {
            if(!isFBServerReady) return;
            logger.warn("设备【{}】的nkAgent失效了，需要重新创建...........", phone.getUdid());
            createNKAgent("回调重试");
            logger.warn("设备【{}】的nkAgent重新创建完成...........", phone.getUdid());
        });
        boolean nkAgentReady = false;
        int reTryTime = 1;
        while (!nkAgentReady && reTryTime <= 5 && isFBServerReady) {
            logger.debug("尝试第{}次连接设备【{}】的nkAgent", reTryTime, phone.getUdid());
            try {
                nkAgent.connect();
                nkAgentReady = nkAgent.getStatus();
                logger.debug("设备【{}】的nkAgent连接完成，结果：{}", phone.getUdid(), nkAgentReady);
            } catch (IOException e) {
                logger.error("第{}次连接设备【{}】的agent出错", reTryTime, phone.getUdid(), e);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ex) {
                    break;
                }
            }
            reTryTime++;
        }
        if (!nkAgentReady) {
            nkAgent.setOnDisconnectListener(null);
            nkAgent = null;
            if (null != process) {
                process.destroy();
            }
            isFBServerReady = false;
            throw new ExecuteException(String.format("无法创建设备【%s】nkAgent", phone.getUdid()));
        }else{
            logger.debug("设置设备【{}】的帧数为：{}", phone.getUdid(), frame);
            nkAgent.setMJPEGServerRate(frame);
        }
        logger.debug("设备【{}】的nkAgent连接完毕................", phone.getUdid());
    }


    public NKAgent getNkAgent() {
        return nkAgent;
    }

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

    public abstract void exitWdaAndProxy();

    protected String getLogFileNameDateTime() {
        Calendar calendar = Calendar.getInstance();
        return String.format("%s%d%d_%d-%d-%d", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
    }

    public void setMJPEGServerRate(int frameRate){
        this.frame = frameRate;
    };


}
