package net.northking.cctp.upperComputer.utils.ios;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import net.northking.cctp.upperComputer.deviceManager.common.PyMobileDevice;
import net.northking.cctp.upperComputer.deviceManager.entity.AppleApplicationInfo;
import net.northking.cctp.upperComputer.deviceManager.thread.IosDeviceInitThread;
import net.northking.cctp.upperComputer.driver.ios.NKAgent;
import net.northking.cctp.upperComputer.driver.ios.command.data.ScreenShotData;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author : yineng.huang
 * @date : 2024/6/12 14:18
 */
public class MacIosHandleHelper extends IosDeviceHandleHelper {

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

    @Override
    public boolean isAppInstalled(String deviceId, String appPackage) {
        PyMobileDevice.SpecificAppleDeviceInfo specificAppleDeviceInfo = IOSDeviceManager.getInstance().getSpecificAppleDeviceInfo(deviceId);
        HashMap<String, AppleApplicationInfo> appMap = PyMobileDevice.getInstance().listApp(specificAppleDeviceInfo, false, true);
        if (null == appMap) {
            logger.warn("没有在设备【{}】上找到app【{}】信息", deviceId, appPackage);
            return false;
        }
        boolean contain = appMap.containsKey(appPackage);
        if (contain) {
            AppleApplicationInfo appleApplicationInfo = appMap.get(appPackage);
            logger.debug("设备【{}】上的app信息：{}", deviceId, JSON.toJSONString(appleApplicationInfo));
            return true;
        }
        return false;
    }

    @Override
    public boolean removeApp(String deviceId, String appPackage) {
        PyMobileDevice.SpecificAppleDeviceInfo specificAppleDeviceInfo = IOSDeviceManager.getInstance().getSpecificAppleDeviceInfo(deviceId);
        boolean success = PyMobileDevice.getInstance().uninstallApp(specificAppleDeviceInfo, appPackage, null);
        logger.debug("设备【{}】卸载app【{}】的结果：{}", deviceId, appPackage, success);
        return success;
    }

    @Override
    public String getOldPackageCode(String deviceId, String appPackage) {
        PyMobileDevice.SpecificAppleDeviceInfo specificAppleDeviceInfo = IOSDeviceManager.getInstance().getSpecificAppleDeviceInfo(deviceId);
        HashMap<String, AppleApplicationInfo> appMap = PyMobileDevice.getInstance().listApp(specificAppleDeviceInfo, false, true);
        if (null == appMap) {
            logger.warn("没有在设备【{}】上找到app【{}】信息", deviceId, appPackage);
            return null;
        }
        boolean contain = appMap.containsKey(appPackage);
        if (contain) {
            AppleApplicationInfo appleApplicationInfo = appMap.get(appPackage);
            logger.debug("设备【{}】上的app信息：{}", deviceId, JSON.toJSONString(appleApplicationInfo));
            return appleApplicationInfo.getCFBundleShortVersionString();
        } else {
            logger.warn("没有在设备【{}】上找到app【{}】信息", deviceId, appPackage);
        }
        return null;
    }

    @Override
    public boolean installApp(String deviceId, String appPath) {
        PyMobileDevice.SpecificAppleDeviceInfo specificAppleDeviceInfo = IOSDeviceManager.getInstance().getSpecificAppleDeviceInfo(deviceId);
        boolean success = PyMobileDevice.getInstance().installApp(specificAppleDeviceInfo, appPath, null);
        logger.debug("设备【{}】安装app【{}】的结果：{}", deviceId, appPath, success);
        return success;
    }

    @Override
    public boolean activateApp(String deviceId, String appPackage) {
        NKAgent nkAgent = getNkAgent(deviceId);
        String bundleId = nkAgent.activeAppBundleId();
        logger.info("设备【{}】的当前启动的应用为【{}】,传过来要启动的应用为【{}】", deviceId, bundleId,appPackage);
        if (bundleId.equals(appPackage)) {
            logger.info("设备【{}】的应用【{}】已经启动并展示在前台", deviceId, appPackage);
            return true;
        }
        logger.info("设备【{}】的应用【{}】未展示在前台,开始启动", deviceId, appPackage);
        boolean success = nkAgent.launchApp(appPackage);
        logger.debug("设备【{}】启动app【{}】的结果：{}",deviceId,appPackage,success);
        return success;
    }


    @Override
    public File getScreenShotFile(String deviceId, Integer startX, Integer startY, Integer cutWidth, Integer cutHeight, Integer screenWidth, Integer screenHeight) {
        if (cutWidth <= 0 || cutHeight <= 0) {
            throw new ExecuteException("截取图片的宽高不满足要求");
        }
        int screenShotTime = 1;
        while (screenShotTime <= 3) {
            logger.debug("设备【{}】第{}次截图开始.................", deviceId, screenShotTime);
            NKAgent nkAgent = getNkAgent(deviceId);
            ScreenShotData screenShotData = nkAgent.screenShot();
            logger.debug("设备【{}】第{}次截图的大小：{}", deviceId, screenShotTime, screenShotData.dataLength);
            if (screenShotData.dataLength > 0) {
                File file = null;
                File screenShotFile = null;
                FileOutputStream fileOutputStream = null;
                try {
                    File picDir = new File(UpperComputerManager.getInstance().getApplicationPath() + "/tempPic");
                    if (!picDir.exists()) {
                        picDir.mkdirs();
                    }
                    screenShotFile = new File(picDir.getAbsolutePath() + "/" + UUID.randomUUID() + ".jpg");
                    fileOutputStream = new FileOutputStream(screenShotFile);
                    fileOutputStream.write(screenShotData.data);
                    fileOutputStream.flush();
                    logger.debug("设备【】第{}次截图在磁盘的位置为：{}", deviceId, screenShotTime, screenShotFile.getAbsolutePath());
                    file = cutImageFile(screenShotFile, deviceId, startX, startY, cutWidth, cutHeight, screenWidth, screenHeight);
                    logger.debug("截取出来的图像为：{}", file.getAbsolutePath());
                    return file;
                } catch (IOException e) {
                    logger.error("截图写入磁盘失败", e);
                } finally {
                    if (null != fileOutputStream) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null != screenShotFile) {
                        //删除
                    }
                    if (null != file) {
                        //删除
                    }
                }
            }
            screenShotTime++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        throw new ExecuteException("设备截图失败");
    }

    private NKAgent getNkAgent(String deviceId) {
        IosDeviceInitThread iosInitThread = IOSDeviceManager.getInstance().getIosInitThread(deviceId);
        if (null == iosInitThread || !iosInitThread.isAlive() || iosInitThread.isInterrupted()) {
            throw new ExecuteException("设备已经掉线，请重新接入设备");
        }
        NKAgent nkAgent = iosInitThread.getNkAgent();
        if (!nkAgent.getStatus()) {
            throw new ExecuteException("设备Agent还未准备好，稍后再试");
        }
        return nkAgent;
    }
}
