package com.example.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class CommandExecute {
    public CommandExecute() {
    }

    public static void main(String[] args) {
        String[] command = new String[]{
                "D:\\Anaconda3\\envs\\python3.10.6\\python.exe",
                "C:\\Users\\EucliwoodHellsycthe\\Desktop\\merge.py"
        };
        executeCommand(command);
    }

    public static String executeCommand(String[] command) {
        StringBuilder output = new StringBuilder();
        StringBuilder errorOutput = new StringBuilder();

        Process p = null;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();

            try (InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8);
                 BufferedReader reader = new BufferedReader(inputStreamReader)) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            try (InputStreamReader errorStreamReader = new InputStreamReader(p.getErrorStream(), StandardCharsets.UTF_8);
                 BufferedReader errorReader = new BufferedReader(errorStreamReader)) {
                String line;
                while ((line = errorReader.readLine()) != null) {
                    errorOutput.append(line).append("\n");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        } finally {
            if (p != null) {
                p.destroy();
            }
        }

        System.out.println("Output:");
        System.out.println(output.toString());
        System.out.println("Error Output:");
        System.out.println(errorOutput.toString());

        return output.toString();
    }
}