package net.northking.cctp.se.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.northking.cctp.element.core.exception.ExecuteException;
import net.northking.cctp.se.device.bean.DebuggerDeviceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;

import java.util.Map;

public class IosUtil {

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

    private static final String IS_APP_INSTALLED = "http://%s/engine/isAppInstalled";
    private static final String REMOVE_APP = "http://%s/engine/removeApp";
    private static final String INSTALL_APP = "http://%s/engine/installApp";
    private static final String ACTIVE_APP = "http://%s/engine/activeApp";
    private static final String TERMINATE_APP = "http://%s/engine/terminateApp";
    private static final String ALL_SCREEN_SHOT_URL = "http://%s/engine/uploadShotAllScreen";
    private static final String START_RECORD_URL = "http://%s/engine/startRecord";
    private static final String END_RECORD_URL = "http://%s/engine/endRecord";

    public static boolean isAppInstalled(String remoteAddress, String deviceId, String appPackage) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setAppPackage(appPackage);
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        try {
            return HttpUtils.doPost(String.format(IS_APP_INSTALLED, remoteAddress), entity, Boolean.class);
        } catch (Exception e) {
            logger.error("设备【{}】查询app是否安装出错", deviceId, e);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
                logger.warn("设备【{}】判断是否安装app前停止。。。。。。。。。。", deviceId);
                throw new ExecuteException("执行停止");
            }
            return HttpUtils.doPost(String.format(IS_APP_INSTALLED, remoteAddress), entity, Boolean.class);
        }
    }

    public static boolean removeApp(String remoteAddress, String deviceId, String appPackage) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setAppPackage(appPackage);
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        try {
            return HttpUtils.doPost(String.format(REMOVE_APP, remoteAddress), entity, Boolean.class);
        } catch (Exception e) {
            logger.error("卸载应用出错", e);
            throw new ExecuteException("卸载设备上App出错");
        }
    }

    public static boolean installApp(String remoteAddress, String deviceId, String appPath,String platform) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setAppPath(appPath);
        info.setPlatform(platform);
        logger.debug("ios install info:{}",JSONObject.toJSONString(info));
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        Boolean isOk = HttpUtils.doInstall(String.format(INSTALL_APP, remoteAddress), entity);
        if (!isOk) {
            logger.warn("设备【{}】安装应用失败。。。。", deviceId);
            throw new ExecuteException("安装App出错");
        }
        return true;
    }

    public static boolean activeApp(String uuid, String appPackage, String remoteAddress) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(uuid);
        info.setAppPackage(appPackage);
        info.setPlatform("1");
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        Boolean isOk = false;
        try {
            isOk = HttpUtils.doPost(String.format(ACTIVE_APP, remoteAddress), entity, Boolean.class);
        } catch (Exception e) {
            logger.error("设备【{}】启动应用失败", uuid,e);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
                logger.warn("设备【{}】关闭app前停止。。。。。。。。。。", uuid);
                throw new ExecuteException("执行停止");
            }
            isOk = HttpUtils.doPost(String.format(ACTIVE_APP, remoteAddress), entity, Boolean.class);
        }
        logger.debug("启动应用结果：{}", isOk);
        if (!isOk) {
            throw new ExecuteException("启动应用失败");
        }
        return true;
    }

    public static boolean terminateApp(String uuid, String appPackage, String remoteAddress) {
        Boolean isOk = false;
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(uuid);
        info.setAppPackage(appPackage);
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        try {
            isOk = HttpUtils.doPost(String.format(TERMINATE_APP, remoteAddress), entity, Boolean.class);
        } catch (Exception e) {
            logger.error("设备【{}】关闭应用失败，重试一次", uuid,e);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
                logger.warn("设备【{}】关闭app前停止。。。。。。。。。。", uuid);
                throw new ExecuteException("执行停止");
            }
            isOk = HttpUtils.doPost(String.format(TERMINATE_APP, remoteAddress), entity, Boolean.class);
        }
        logger.debug("关闭应用结果：{}", isOk);
        if (!isOk) {
//            throw new ExecuteException("关闭应用失败");
        }
        return true;
    }


    public static String startRecord(String remoteAddress, String deviceId, String taskId, String resolution) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setPlatform("1");
        logger.info("移动任务开启录屏，任务id:" + taskId);
        info.setTaskId(taskId);
        info.setResolution(resolution);
        logger.info("录屏参数：{}", JSON.toJSONString(info));
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        String result = null;
        try {
            result = HttpUtils.doPost(String.format(START_RECORD_URL, remoteAddress), entity, String.class);
        } catch (Exception e) {
            logger.error("开启录屏失败", e);
        }
        return result;
    }

    public static String stopRecord(String remoteAddress, String deviceId, Map<String, Object> initData) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        Boolean save = (Boolean) initData.get("save");
        info.setDeviceId(deviceId);
        info.setPlatform("1");
        logger.info("移动任务结束录屏，任务id:" + initData.get("taskId"));
        info.setTaskId(initData.get("taskId").toString());
        info.setTenantId(initData.get("tenantId").toString());
        info.setSave(save);
        logger.info("结束录屏参数：{}", JSON.toJSONString(info));
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        String result = null;
        try {
            result = HttpUtils.doPost(String.format(END_RECORD_URL, remoteAddress), entity, String.class);
        } catch (Exception e) {
            logger.error("结束录屏失败", e);
        }
        return result;
    }
}
