package net.northking.cctp.se.util;

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

import java.util.Map;

public class AndroidUtil {

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

    private static final String CLEAN_APP_DATA_URL = "http://%s/engine/cleanData";
    private static final String GET_PACKAGE_VERSION_URL = "http://%s/engine/getPackageVersion";
    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";
    private static final String INSTALL_APP = "http://%s/engine/installApp";
    private static final String ACTIVE_APP = "http://%s/engine/activeApp";

    public static boolean cleanAppData(String remoteAddress,String deviceId,String appPackage){
        try {
            DebuggerDeviceInfo info = new DebuggerDeviceInfo();
            info.setDeviceId(deviceId);
            info.setAppPackage(appPackage);
            HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
            return HttpUtils.doPost(String.format(CLEAN_APP_DATA_URL, remoteAddress),entity, Boolean.class);
        } catch (Exception e) {
            logger.error("清除数据失败，原因：{}",e);
            return false;
        }
    }

    /**
     * 获取手机应用版本号
     * @param deviceId
     * @param appPackage
     * @return
     */
    public static String getOldPackageCode(String remoteAddress,String deviceId,String appPackage,String platform){
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setAppPackage(appPackage);
        info.setPlatform(platform);
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        try {
            return HttpUtils.doPost(String.format(GET_PACKAGE_VERSION_URL, remoteAddress),entity, String.class);
        } catch (Exception e) {
            logger.error("获取应用版本号失败，原因：{}",e);
            return "";
        }
    }

    public static String startRecord(String remoteAddress,String deviceId,String taskId){
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        info.setPlatform("0");
        logger.info("移动任务开启录屏，任务id:"+taskId);
        info.setTaskId(taskId);
        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) {
        String tenantId = (String)initData.get("tenantId");
        Boolean save = (Boolean) initData.get("save");
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setDeviceId(deviceId);
        String taskId = (String)initData.get("taskId");
        logger.info("移动任务结束录屏，任务id:"+taskId);
        info.setTaskId(taskId);
        info.setTenantId(tenantId);
        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;
    }



    public static String snapshotAllScreen(String remoteAddress, DeviceInfo deviceInfo, String tenantId, String taskId) {
        DebuggerDeviceInfo info = new DebuggerDeviceInfo();
        info.setPlatform(deviceInfo.getPlatform());
        info.setDeviceId(deviceInfo.getDeviceId());
        info.setResolution(deviceInfo.getResolution());
        info.setTenantId(tenantId); //租户id
        info.setTaskId(taskId);
        logger.info("参数：{}", JSON.toJSONString(info));
        HttpEntity<DebuggerDeviceInfo> entity = new HttpEntity<>(info);
        String result = null;
        try {
            result = HttpUtils.doPost(String.format(ALL_SCREEN_SHOT_URL, remoteAddress), entity, String.class);
        } catch (Exception e) {
            logger.error("截图失败",e);
        }
        return result;
    }

    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);
        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("0");
        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;
    }
}
