package istlab.KisoJikken;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class ShellScriptPanel extends JPanel implements ActionListener, Runnable {
    JTextArea jta;
    JScrollPane jsp;
    JLabel lbl;
    String script;
    JButton execB;
    Thread thread;
    Process process;

    // private Thread stdOutReader;
    // private Thread stdErrReader;
    // private boolean stopThreads;
    // private final PipedInputStream stdOutPin = new PipedInputStream();
    // private final PipedInputStream stdErrPin = new PipedInputStream();

    public ShellScriptPanel(String script) {
        setLayout(new BorderLayout());
        this.script = script;
        jta = new JTextArea();
        jta.setEditable(false);
        jsp = new JScrollPane(jta);
        add(jsp);
        lbl = new JLabel(script);
        add(lbl, BorderLayout.NORTH);

        execB = new JButton("Run / Stop");
        execB.addActionListener(this);
        add(execB, BorderLayout.SOUTH);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (thread == null) {
            thread = new Thread(this);
            thread.start();
        } else {
            process.destroy();
            thread = null;
        }
    }

    @Override
    public void run() {
        // Run script
        String userHomeDir = System.getProperty("user.home");
        System.out.println(userHomeDir + "/NWP/src/" + script);
        ProcessBuilder processBuilder = new ProcessBuilder("bash", userHomeDir + "/NWP/src/" + script);
        // ProcessBuilder processBuilder = new ProcessBuilder("pwd");
        processBuilder.directory(new File(userHomeDir+"/NWP/src"));
        processBuilder.inheritIO();
        try {
            process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                jta.append(line);
            }
            process.waitFor();
        } catch (IOException | InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("Exit");
        thread = null;
    }

}
