package net.northking.cctp.upperComputer.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author: WuJinQuan
 * @date:2021-09-08 15:14
 **/
public class IosTiDeviceThread extends Thread {
    private final static Logger logger = LoggerFactory.getLogger(IosTiDeviceThread.class);
    private Process p = null;
    private InputStream is1 = null;
    private String redisKey;
    private String shell;
    private String iosPerShellTemplate = "tidevice -u %s perf -B %s";
    private IosPerfDataRead iosPerfDataRead;

    public IosTiDeviceThread() {
    }

    public void initData(Map<String, String> map) {
        String detailId = map.get("detailId");//性能获取id
        String serial = map.get("serial");//设备号
        String appPackage = map.get("package");//设备号
        this.redisKey = "cctp-mobile:perf:" + detailId + "-" + serial;
        this.shell = String.format(this.iosPerShellTemplate, serial, appPackage);
        logger.info("获取ios命令：{}",this.shell);
        startApp(serial, appPackage);
    }


    private ProcessBuilder builder = new ProcessBuilder();

    private Process process;
    private List<String> historyMsgList = Collections.synchronizedList(new ArrayList<>());
    private List<String> historyCmdList = new ArrayList<>();
    private Queue<String> msgQueue = new ConcurrentLinkedQueue<>();
    private PrintWriter writer;
    private BufferedReader stdoutReader;

    public boolean isWindows() {
        return System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1;
    }

    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        logger.info("开始执行时间：{}", LocalDateTime.now());
        //执行打印
        try {
            logger.info(shell);
            p=Runtime.getRuntime().exec(shell);
            long exeShellTime = System.currentTimeMillis();
            logger.info("执行花费时间：{} ms", (exeShellTime-startTime));
        } catch (IOException e) {
            logger.error("执行脚本失败",e);
        }
        //获取进程的标准输入流
        is1 = p.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(is1);
        long getInputStreamTime = System.currentTimeMillis();
        logger.info("inputStreamReader 流花费时间：{} ms", (getInputStreamTime-startTime));
        BufferedReader reader = new BufferedReader(inputStreamReader);
        long bufferedReaderTime = System.currentTimeMillis();
        logger.info("bufferedReader 流花费时间：{} ms", (bufferedReaderTime-startTime));
        try {
            logger.info("输出信息？{}",reader.readLine());
        } catch (IOException e) {
            logger.error("reader数据获取失败",e);
        }
        iosPerfDataRead=new IosPerfDataRead();
        iosPerfDataRead.init(reader,redisKey);
        iosPerfDataRead.run();
        long initSocketStreamTime = System.currentTimeMillis();
        logger.info("运行花费时间：{} 秒", (initSocketStreamTime-startTime)/1000);
        try{
            Thread.sleep(2000);
            iosPerfDataRead.stopRead();
            p.destroyForcibly();
        }catch (Exception e){
            logger.error("线程停止失败",e);
        }
    }

    private void startApp(String serial, String PackageName) {
        Process proc = null;
        try {
            Runtime runtime = Runtime.getRuntime();
            String pro = "tidevice -u " + serial + " launch " + PackageName;
            proc = runtime.exec(pro);
            logger.info(pro);
            if (proc.waitFor() != 0) {
            }
        } catch (Exception e) {
            logger.error("startApp失败",e);
        }
    }

    public void stopThread() throws Exception {
        iosPerfDataRead.stopRead();
        p.destroy();
    }
}
