package net.geedge.api.util;

import net.geedge.common.APIException;
import net.geedge.common.RCode;
import net.geedge.common.T;

import java.io.*;
import java.util.List;
import java.util.stream.Collectors;

public class CommandExec {

        private File logFile;
        private ProcessBuilder processBuilder;

        public String exec(List<String> command) {

            if (logFile != null) {
                T.FileUtil.appendString(T.StrUtil.concat(true, "$ ", command.stream().collect(Collectors.joining(" ")), "\n"), this.logFile, "UTF-8");
            }

            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            StringBuilder stringBuilder = null;
            Process process = null;
            InputStream inputStream = null;
            try {
                process = processBuilder.command(command).start();
                stringBuilder = new StringBuilder();
                inputStream = process.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (logFile != null) {
                        // 处理每一行输出
                        T.FileUtil.appendString(T.StrUtil.concat(true, line, "\n"), this.logFile, "UTF-8");
                    }
                    stringBuilder.append(line).append(System.lineSeparator());
                }
            } catch (Exception e) {
                throw new APIException(RCode.ERROR);
            }finally {
                if (process != null) {
                    process.destroy();
                }
                T.IoUtil.close(inputStreamReader);
                T.IoUtil.close(bufferedReader);
                T.IoUtil.close(inputStream);
            }

            return stringBuilder.toString().stripTrailing();
        }

        public Process execForProcess(List<String> command) {
            Process process = T.RuntimeUtil.exec(command.stream().toArray(String[]::new));
            return process;
        }

        public CommandExec(File logFile ) {
            this.logFile = logFile;
            this.processBuilder = new ProcessBuilder();
        }
    }