package net.northking.cctp.upperComputer.utils.deviceHepler.harmony;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.upperComputer.deviceManager.HarmonyDeviceManager;
import net.northking.cctp.upperComputer.deviceManager.thread.HarmonyProvider;
import net.northking.cctp.upperComputer.driver.harmony.HarmonyDevice;
import net.northking.cctp.upperComputer.driver.harmony.hdc.HDCConnectStatus;
import net.northking.cctp.upperComputer.driver.harmony.hdc.HDCSession;
import net.northking.cctp.upperComputer.driver.harmony.hdc.Hdc;
import net.northking.cctp.upperComputer.exception.ExecuteException;
import net.northking.cctp.upperComputer.utils.deviceHepler.AbstractDeviceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @author : yineng.huang
 * @date : 2024/10/29 17:44
 */
public class HarmonyHandlerHelper extends AbstractDeviceHelper {

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

    private final String IS_APP_INSTALLED = "bm dump -n %s";
    private final String START_APP = "aa start -a %s -b %s";
    private final String TERMINATE_APP = "aa force-stop %s";
    private final String CLEAN_DATA = "bm clean -d -n %s";


    @Override
    public boolean cleanData(String deviceId, String appPackage) {
        HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
        HDCSession shell = Hdc.getInstance().shell(harmonyDevice.getHdcDevice(), String.format(CLEAN_DATA, appPackage));
        String result = shell.readAllLines();
        if (result != null && result.contains("successfully")) {
            return true;
        } else {
            logger.debug("停止设备【{}】应用返回结果：{}",deviceId,result);
            return false;
        }
    }

    @Override
    public boolean isAppInstalled(String deviceId, String appPackage) {
        JSONObject appInfo = getAppInfo(deviceId, appPackage);
        if (null != appInfo) {
            return true;
        }
        return false;
    }

    @Override
    public boolean removeApp(String deviceId, String appPackage) {
        HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
        return Hdc.getInstance().uninstall(harmonyDevice.getHdcDevice(), appPackage, false, true);
    }

    @Override
    public boolean terminateApp(String deviceId, String appPackage) {
        HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
        HDCSession shell = Hdc.getInstance().shell(harmonyDevice.getHdcDevice(), String.format(TERMINATE_APP, appPackage));
        String result = shell.readAllLines();
        if (result != null && result.contains("force stop process successfully")) {
            return true;
        } else {
            logger.debug("停止设备【{}】应用返回结果：{}",deviceId,result);
            return false;
        }
    }

    @Override
    public String getOldPackageCode(String deviceId, String appPackage) {
        JSONObject appInfo = getAppInfo(deviceId, appPackage);
        if (null == appInfo) {
            return null;
        } else {
            String versionCode = appInfo.getString("versionName");
            logger.debug("得到设备【{}】上应用【{}】的版本为:{}",deviceId,appPackage,versionCode);
            return versionCode;
        }
    }

    @Override
    public boolean installApp(String deviceId, String appPath) {
        HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
        return Hdc.getInstance().install(harmonyDevice.getHdcDevice(),new File(appPath));
    }

    @Override
    public boolean activateApp(String deviceId, String appPackage) {
        JSONObject appInfo = getAppInfo(deviceId, appPackage);
        if (null == appInfo) {
            logger.warn("设备【{}】上不存在应用【{}】", deviceId, appPackage);
            return false;
        } else {
            JSONArray hapModuleInfos = appInfo.getJSONArray("hapModuleInfos");
            String mainAbility = null;
            if (!CollectionUtils.isEmpty(hapModuleInfos)) {
                for (Object hapModuleInfo : hapModuleInfos) {
                    JSONObject moduleInfo = JSONObject.parseObject(JSONObject.toJSONString(hapModuleInfo));
                    mainAbility = moduleInfo.getString("mainAbility");
                    if (StringUtils.hasText(mainAbility)) {
                        break;
                    }
                }
            }
            logger.warn("拿到设备【{}】应用【{}】的mainAbility为：{}", deviceId, appPackage,mainAbility);
            if (null == mainAbility || StringUtils.isEmpty(mainAbility)) {
                logger.warn("设备【{}】上无法找到应用【{}】的mainAbility，应用无法启动", deviceId, appPackage);
                return false;
            }
            HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
            HDCSession shell = Hdc.getInstance().shell(harmonyDevice.getHdcDevice(), String.format(START_APP, mainAbility,appPackage));
            String result = shell.readAllLines();
            if (result.contains("start ability successfully")) {
                return true;
            } else {
                logger.warn("设备【{}】上启动应用【{}】失败，执行命令的结果：{}", deviceId, appPackage,result);
                return false;
            }
        }
    }

    @Override
    public File getScreenShotFile(String serial) {
        HarmonyDevice harmonyDevice = getHarmonyDevice(serial);
        File cutFilePath = new File(System.getProperty("user.dir") + "/tempPic");
        if (!cutFilePath.exists()) {
            cutFilePath.mkdirs();
        }
        String localPic = cutFilePath.getAbsolutePath() + "/" + System.currentTimeMillis() + ".png";
        File file = harmonyDevice.takeScreenshotForFile(localPic);
        return file;
    }

    @Override
    public File getScreenShotFile(String deviceId, Integer startX, Integer startY, Integer cutWidth, Integer cutHeight, Integer screenWidth, Integer screenHeight,int width,int height) {
        if (cutWidth <= 0 || cutHeight <= 0) {
            throw new ExecuteException("截取图片的宽高不满足要求");
        }
        File snapShotFile = null;
        File cutFile = null;
        try {
            snapShotFile = getScreenShotFile(deviceId);
            if (null == snapShotFile) {
                logger.debug("设备【{}】未截取到图片",deviceId);
                throw new ExecuteException("未截取到图片");
            }
            cutFile = cutImageFile(snapShotFile, deviceId, startX, startY, cutWidth, cutHeight, screenWidth, screenHeight,width,height);
            logger.debug("设备【{}】截取到的图片为：{}",deviceId,cutFile.getAbsolutePath());
            return cutFile;
        } catch (ExecuteException e) {
            logger.error("截图失败", e);
            throw e;
        } catch (Exception e) {
            logger.error("截图失败", e);
            throw new ExecuteException("截取图片失败");
        }finally {
            if (null != snapShotFile) {
                //删除
            }
            if (null != cutFile) {
                //删除
            }
        }
    }

    private HarmonyProvider getProvider(String deviceId){
        HarmonyProvider currentDeviceProvider = HarmonyDeviceManager.getInstance().getCurrentDeviceProvider(deviceId);
        if (null == currentDeviceProvider) {
            logger.warn("设备【{}】已经掉线了，稍后再试.......",deviceId);
            throw new ExecuteException("当前设备已经掉线，请稍后再试");
        }
        return currentDeviceProvider;
    }

    private HarmonyDevice getHarmonyDevice(String deviceId) {
        HarmonyDevice currentDevice = HarmonyDeviceManager.getInstance().getCurrentDevice(deviceId);
        if (null == currentDevice || currentDevice.getHdcDevice().getConnectStatus() != HDCConnectStatus.CONNECTED){
            throw new ExecuteException("当前设备已经掉线，请稍后再试");
        }
        return currentDevice;
    }

    private JSONObject getAppInfo(String deviceId,String appPackage){
        HarmonyDevice harmonyDevice = getHarmonyDevice(deviceId);
        HDCSession shell = Hdc.getInstance().shell(harmonyDevice.getHdcDevice(), String.format(IS_APP_INSTALLED, appPackage));
        String result = shell.readAllLines();
        if (result.contains("failed to get information")) {
            return null;
        } else {
            int index = result.indexOf("{");
            String str = result.substring(index);
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(str, JSONObject.class);
            } catch (Exception e) {
                logger.error("转换app信息失败，得到的结果为：{}",str);
            }
            return jsonObject;
        }
    }
}
