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

import cn.hutool.extra.spring.SpringUtil;
import net.northking.cctp.upperComputer.deviceManager.UpperComputerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : yineng.huang
 * @date : 2024/4/12 15:51
 */
public class UsbMuxdDriverThread extends Thread {
    private Logger logger = LoggerFactory.getLogger(UsbMuxdDriverThread.class);

    private Process startProcess;

    private String password;

    public UsbMuxdDriverThread() {
        password =  SpringUtil.getProperty("nk.mobile-computer.password");
        logger.debug("已保存用户密码：{}",password);
        setName("[usbmuxd线程]");
    }

    @Override
    public void run() {
        ProcessBuilder builder = new ProcessBuilder(new String[]{"sh", "-c", "ps -ef | grep usbmuxd"}).redirectErrorStream(true);
        BufferedReader reader = null;
        String line = null;
        List<String> result = new ArrayList<>();
        List<String> process = new ArrayList<>();
        try {
            Process findUsbMuxdProcess = builder.start();
            reader = new BufferedReader(new InputStreamReader(findUsbMuxdProcess.getInputStream()));
            while ((line = reader.readLine()) != null) {
                logger.debug("查找usbmuxd进程结果：{}",line);
                String[] split = line.split(" ");
                for (String s : split) {
                    if (StringUtils.hasText(s)) {
                        result.add(s);
                    }
                }
                process.add(result.get(1));   //第二个是进程
            }
        } catch (IOException e) {
            logger.warn("查询usbmuxd进程出错", e);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {

            }
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (!CollectionUtils.isEmpty(process)) {
            for (String processItem : process) {
                logger.debug("杀掉usbmuxd进程：{}", processItem);
                String [] cmds = new String[]{"/bin/bash", "sudo -S kill -9 "+processItem};
                ProcessBuilder killBuilder = new ProcessBuilder(cmds).redirectErrorStream(true);
                Process killProcess = null;
                try {
                    killProcess = killBuilder.start();
                    OutputStream outputStream = killProcess.getOutputStream();
                    outputStream.write((password + "\n").getBytes());
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("关闭usbmuxd时，输入密码出错.....",e);
                }
            }
        } else {
            logger.debug("没有查询到有usbmuxd进程.........");
        }
        logger.info("启动usbmuxd进程....................");
        String [] cmds = new String[]{"/bin/bash", "sudo usbmuxd -f"};
        File logPath = new File(UpperComputerManager.getInstance().getApplicationPath() + "/usbMuxdLog");
        if (!logPath.exists()) {
            logPath.mkdirs();
        }
        File logFile = new File(logPath.getAbsolutePath() + "/usbMuxd.log");
        FileWriter fileWriter = null;
        BufferedWriter writer = null;
        ProcessBuilder startProcessBuilder = new ProcessBuilder(cmds).redirectErrorStream(true);
        while (!isInterrupted()) {
            try {
                startProcess = startProcessBuilder.start();
                fileWriter = new FileWriter(logFile,true);
                writer = new BufferedWriter(fileWriter);
                reader = new BufferedReader(new InputStreamReader(startProcess.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                    writer.newLine();
                    writer.flush();
                    if ("Initialization complete".equals(line)) {
                        logger.info("usbmuxd已经启动完成............");
                    }
                }
            } catch (IOException e) {
                logger.warn("usbmuxd日志写入失败。。。。。。。", e);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex) {
                    interrupt();
                    break;
                }
            }
        }

    }

    public void exitUsbMuxd() {
        interrupt();
        if (startProcess != null) {
            startProcess.destroyForcibly();
        }
    }
}
