package com.yutou.bilibili.Tools;

import com.yutou.common.utils.AppTools;
import com.yutou.common.utils.Base64Tools;
import com.yutou.common.utils.Log;
import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;


public class ProcessUtils {
    public static boolean isRuntimeSystemOfWindow() {
        return System.getProperty("os.name").contains("Windows");
    }

    public static void killProcess(Long pid) throws Exception {
        if (pid == null) {
            return;
        }
        if (isRuntimeSystemOfWindow()) {
            // 对于 Windows 系统
            Process process = exec("taskkill /F /PID " + pid);
            process.waitFor();
        } else {
            // 对于 Linux 和 macOS 系统
            Process process = exec("kill -9 " + pid);
            process.waitFor();
        }

    }

    public static boolean isProcessRunning(Long pid) throws Exception {
        if (pid == null) {
            return false;
        }
        String[] command;
        if (isRuntimeSystemOfWindow()) {
            // Windows 操作系统
            command = new String[]{"cmd.exe", "/c", "tasklist /FI \"PID eq " + pid + "\""};
        } else {
            // Unix/Linux 操作系统
            command = new String[]{"sh", "-c", "ps -p " + pid};
        }

        Process process = Runtime.getRuntime().exec(command);
        boolean isRunning = false;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(String.valueOf(pid))) {
                    isRunning = true;
                }
            }
            reader.close();
            process.destroy();
        } catch (Exception e) {
            Log.e(e);
        }

        return isRunning;
    }

    public static Process exec(String exec) throws Exception {
        if (isRuntimeSystemOfWindow()) {
            return exec("cmd.exe", "/c", exec);
        } else {
            return exec("sh", "-c", exec);
        }
    }

    public static Process exec(String... command) throws Exception {
        ProcessBuilder pb;
        List<String> list = Arrays.stream(command).map(Base64Tools::decode).toList();
        pb = new ProcessBuilder(list);
        return pb.start();
    }

    public static void main(String[] args) throws Exception {
    }
}
