package net.northking.cctp.upperComputer.deviceManager.thread;

import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @author : yineng.huang
 * @date : 2023/11/30 17:31
 */
public class AppiumEnvironmentThread extends Thread {

    private Logger logger = LoggerFactory.getLogger(AppiumEnvironmentThread.class);

    private String path;

    private String port;

    private Process appiumProcess;

    public AppiumEnvironmentThread(String path, String port) {
        this.path = path;
        this.port = port;
        setName("[appium线程]");
    }

    @Override
    public void run() {
        logger.info("appium的位置：{},端口：{}", path, port);
        String[] cmd = {"node", ".", "-p", port, "--log-timestamp", "--local-timezone"};
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList(cmd)).redirectErrorStream(true).directory(new File(path));
        File logPath = new File(UpperComputerManager.getInstance().getApplicationPath() + "/appiumLog");
        if (!logPath.exists()) {
            logPath.mkdirs();
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String format = simpleDateFormat.format(new Date());
        File logFile = new File(logPath.getAbsolutePath() + "/appium-" + format + ".log");
        FileWriter fileWriter = null;
        BufferedWriter writer = null;
        BufferedReader reader = null;
        try {
            fileWriter = new FileWriter(logFile);
            writer = new BufferedWriter(fileWriter);
        } catch (IOException e) {
            logger.warn("appium日志写入失败。。。。。。。", e);
            System.exit(1);
        }
        String line;
        try {
            while (!interrupted()) {
                appiumProcess = builder.start();
                reader = new BufferedReader(new InputStreamReader(appiumProcess.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                    writer.newLine();
                    writer.flush();
                    if (line.contains("Appium REST http interface listener started on")) {
                        logger.info("appium启动完成，监听端口：{}", port);
                    } else if (line.contains("address already in use")) {
                        logger.info("appium端口：{}已经被使用！", port);
                        System.exit(1);
                    }
                }

            }
            logger.info("appium程序退出。。。。。");
        } catch (IOException e) {
            logger.warn("appium程序开启失败", e);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("关闭数据流失败，e",e);
                }
            }
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    logger.error("关闭数据流失败，e",e);
                }
            }
            if (null != fileWriter) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    logger.error("关闭数据流失败，e",e);
                }
            }
        }
    }

    public void exitAppium(){
        interrupt();
        if (appiumProcess != null) {
            appiumProcess.destroyForcibly();
        }
    }
}
