package com.my.core.commandManager.util;

import com.my.core.commandManager.data.CommandTasker;
import com.my.core.commandManager.handler.OutHandler;
import com.my.core.commandManager.handler.OutHandlerMethod;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 命令行操作工具类
 *
 * @author eguid
 */
public class ExecUtil {

    /**
     * 执行命令行并获取进程
     *
     * @param cmd
     * @return
     * @throws IOException
     */
    public static Process exec(String cmd,String rtsp,String media) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(cmd);// 执行命令获取主进程
        return process;
    }

//    public static Process exec(String cmd,String rtsp,String media) throws IOException {
////        Runtime runtime = Runtime.getRuntime();
////        Process process = runtime.exec(cmd);// 执行命令获取主进程
//        String allPath = "/usr/local/nginx/html/hls/"+media+".m3u8";
//        //设置第三方应用命令
//        List<String> list = new ArrayList<>();
//        list.add("ffmpeg");
//        list.add("-i");
////        list.add("rtsp://admin:hmkj6688@192.168.1.109");
//        list.add("rtsp://"+rtsp);
//        list.add("-c");
//        list.add("copy");
//        list.add("-f");
//        list.add("hls");
//        list.add("-hls_time");
//        list.add("2.0");
//        list.add("-hls_list_size");
//        list.add("1");
//        list.add("-hls_wrap");
//        list.add("15");
////        list.add("/usr/local/nginx/html/hls/test.m3u8");
//        list.add(allPath);
//        System.out.println("## list="+list.toString());
//        //
//        Process process = run(list);
//        return process;
//    }

    public static Process run(List cmdList) throws IOException {
        //创建processBuilder对象
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(cmdList);
        //将标准输入流和错误流合并
        processBuilder.redirectErrorStream(true);
        //启动一个进程
        Process process = processBuilder.start();
        List<String> listOut = processBuilder.command();
        System.out.println(">>"+listOut.toString());

        //判断子进程是否存在
//        process.isAlive();
        //杀死子进程
//        process.destroy();

        //===================================================================================
        //下面没有输出也能正常输出

        //通过标准输入流拿到正常错误的信息
        InputStream inputStream = process.getInputStream();
        //转成字符流输出
        InputStreamReader reader = new InputStreamReader(inputStream, "GBK");
        //缓冲
        char[] chars = new char[1024];
        int len = -1;
        while ((len = reader.read(chars)) != -1) {
            String string = new String(chars, 0, len);
            System.out.println(string);
        }
        //关流
        reader.close();
        inputStream.close();

        return process;
    }

    /**
     * 销毁进程
     *
     * @param process
     * @return
     */
    public static boolean stop(Process process) {
        if (process != null) {
            process.destroy();
//            process.exitValue();
            return true;
        }
        return false;
    }

    /**
     * 销毁输出线程
     *
     * @param outHandler
     * @return
     */
    public static boolean stop(Thread outHandler) {
        if (outHandler != null && outHandler.isAlive()) {
            outHandler.stop();
            outHandler.destroy();
            return true;
        }
        return false;
    }

    public static void stop(CommandTasker tasker) {
        if (tasker != null) {
            stop(tasker.getThread());
            stop(tasker.getProcess());
        }
    }

    /**
     * 创建命令行任务
     *
     * @param id
     * @param command
     * @return
     * @throws IOException
     */
    public static CommandTasker createTasker(String id, String command, OutHandlerMethod ohm, String rtsp, String media) throws IOException {
        // 执行本地命令获取任务主进程
        Process process = exec(command,rtsp,media);
        System.out.println("执行------------------------------------->");
        // 创建输出线程
        OutHandler outHandler = OutHandler.create(process.getErrorStream(), id, ohm);

        CommandTasker tasker = new CommandTasker(id, command, process, outHandler);

        return tasker;
    }

    /**
     * 中断故障缘故重启
     *
     * @param tasker
     * @return
     * @throws IOException
     */
    public static CommandTasker restart(CommandTasker tasker) throws IOException {
        if (tasker != null) {
            String id = tasker.getId(), command = tasker.getCommand();
            OutHandlerMethod ohm = null;
            if (tasker.getThread() != null) {
                ohm = tasker.getThread().getOhm();
            }
            String rtsp = tasker.getRtsp();
            String media = tasker.getMedia();

            //安全销毁命令行进程和输出子线程
            stop(tasker);
            // 执行本地命令获取任务主进程
            Process process = exec(command,rtsp,media);
            tasker.setProcess(process);
            // 创建输出线程
            OutHandler outHandler = OutHandler.create(process.getErrorStream(), id, ohm);
            tasker.setThread(outHandler);
        }
        return tasker;
    }
}
