package net.northking.cctp.upperComputer.service;

import net.northking.cctp.upperComputer.thread.AndroidAdbDataThread;
import net.northking.cctp.upperComputer.thread.IosTiDeviceThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class DeviceServiceImpl implements DeviceService{

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

    private final String WDA_URL = "http://127.0.0.1:%s";
    //ios获取屏幕参数地址
    private final String IOS_SCREEN_SCALE = "http://127.0.0.1:%s/window/size_stf";

    private static ConcurrentHashMap<String, IosTiDeviceThread> iosPerMap = new ConcurrentHashMap<>(16);//key：设备号 value：性能获取线程

    private static ConcurrentHashMap<String, AndroidAdbDataThread> androidPerMap = new ConcurrentHashMap<>(16);//key：设备号 value：性能获取线程

    @Autowired
    private ApplicationContext context;

    @Override
    public void restartDevice(List<Map<String, String>> deviceList) {
        if (!CollectionUtils.isEmpty(deviceList)) {
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.redirectErrorStream(true);
            for (Map<String,String> deviceMap : deviceList) {
                if ("0".equals(deviceMap.get("platform"))) {   //android重启
                    String[] cmd = {"adb", "-s", deviceMap.get("deviceId"), "reboot"};
                    processBuilder.command(cmd);
                } else if ("1".equals(deviceMap.get("platform"))) {  //ios重启
                    String[] cmd = {"tidevice", "-u", deviceMap.get("deviceId"), "reboot"};
                    processBuilder.command(cmd);
                }
                try {
                    Process process = processBuilder.start();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line = null;
                    logger.debug("重启设备【{}】命令输出：",deviceMap.get("deviceId"));
                    while (null != (line = reader.readLine())) {
                        logger.debug(line);
                    }
                } catch (IOException e) {
                    logger.error("重启设备【{}】命令执行失败！",deviceMap.get("deviceId"));
                }
            }
        }
    }

    /**
     * 性能数据获取
     * @param perDataInfo
     */
    @Override
    public void startPerData(Map<String, String> perDataInfo) {
        try {
            String type = perDataInfo.get("platform");
            String serial=perDataInfo.get("serial");
            //根据设备类型进行数据获取
            if ("ios".equals(type)) {
                IosTiDeviceThread iosTiDeviceThread;
                // 如果有该设备性能线程在执行
                if (iosPerMap.get(serial)!=null){
                    iosTiDeviceThread=iosPerMap.get(serial);
                    iosTiDeviceThread.stopThread();
                }
                iosTiDeviceThread =new IosTiDeviceThread();
                iosTiDeviceThread.initData(perDataInfo);
                logger.info("获取当前APP占用设备信息脚本启动");
                iosTiDeviceThread.start();
                iosPerMap.put(serial, iosTiDeviceThread);
            } else {
                AndroidAdbDataThread androidAdbDataThread;
                if (androidPerMap.get(serial)!=null){//如果有该设备性能线程在执行
                    androidAdbDataThread=androidPerMap.get(serial);
                    androidAdbDataThread.stopThread();
                }
                androidAdbDataThread =new AndroidAdbDataThread();
                androidAdbDataThread.init(perDataInfo);
                androidAdbDataThread.start();
                androidPerMap.put(serial, androidAdbDataThread);
            }
        } catch (Exception e) {
            logger.error("性能数据开启失败..............",e);
        }
    }

    @Override
    public void stopPerData(String serial) {
        try {
            IosTiDeviceThread deviceGetData = iosPerMap.remove(serial);
            if (deviceGetData != null) {
                logger.debug("关闭"+serial+"设备ios获取性能线程");
                deviceGetData.stopThread();
                deviceGetData.interrupt();
            }
            AndroidAdbDataThread adbDataThread=androidPerMap.remove(serial);
            if (adbDataThread != null) {
                logger.debug("关闭"+serial+"设备安卓性能线程");
                adbDataThread.stopThread();
                adbDataThread.interrupt();
            }
        } catch (Exception e) {
            logger.error("手机：{}关闭性能失败",serial);
        }
    }
}
