package com.pty4j;

import com.pty4j.unix.Pty;
import com.pty4j.unix.UnixPtyProcess;
import com.pty4j.util.PtyUtil;
import com.pty4j.windows.CygwinPtyProcess;
import com.pty4j.windows.WinPtyProcess;
import com.sun.jna.Platform;
import com.sun.jna.platform.win32.Advapi32Util;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

public class PtyProcessBuilder {
  private String[] myCommand;
  private Map<String, String> myEnvironment;
  private String myDirectory;
  private boolean myConsole;
  private boolean myCygwin;
  private File myLogFile;

  public PtyProcessBuilder(@NotNull String[] command) {
    myCommand = command;
  }

  public void setCommand(@NotNull String[] command) {
    myCommand = command;
  }

  @NotNull
  public PtyProcessBuilder setEnvironment(@Nullable Map<String, String> environment) {
    myEnvironment = environment;
    return this;
  }

  @NotNull
  public PtyProcessBuilder setDirectory(String directory) {
    myDirectory = directory;
    return this;
  }

  @NotNull
  public PtyProcessBuilder setConsole(boolean console) {
    myConsole = console;
    return this;
  }

  @NotNull
  public PtyProcessBuilder setCygwin(boolean cygwin) {
    myCygwin = cygwin;
    return this;
  }

  @NotNull
  public PtyProcessBuilder setLogFile(@Nullable File logFile) {
    myLogFile = logFile;
    return this;
  }

  @NotNull
  public PtyProcess start() throws IOException {
    if (Platform.isWindows()) {
      Map<String, String> environment = myEnvironment;
      if (environment == null) {
        environment = new TreeMap<String, String>();
      }
      if (myCygwin) {
        return new CygwinPtyProcess(myCommand, environment, myDirectory, myLogFile, myConsole);
      }
      return new WinPtyProcess(myCommand, Advapi32Util.getEnvironmentBlock(environment), myDirectory, myConsole);
    }
    return new UnixPtyProcess(myCommand, PtyUtil.toStringArray(myEnvironment), myDirectory, new Pty(myConsole), myConsole ? new Pty() : null);
  }
}

@@ -673,16 +673,65 @@
 LogFile;
+%0A  private boolean myRedirectErrorStream = false;
 %0A%0A  publ
@@ -1509,32 +1509,195 @@
 turn this;%0A  %7D%0A%0A
+  @NotNull%0A  public PtyProcessBuilder setRedirectErrorStream(boolean redirectErrorStream) %7B%0A    myRedirectErrorStream = redirectErrorStream;%0A    return this;%0A  %7D%0A%0A
   @NotNull%0A  pub
@@ -2163,24 +2163,137 @@
 ole);%0A    %7D%0A
+    Pty pty = new Pty(myConsole);%0A    Pty errPty = myRedirectErrorStream ? pty : (myConsole ? new Pty() : null);%0A
     return n
@@ -2376,56 +2376,19 @@
 ry, 
-new Pty(myConsole), myConsole ? new Pty() : null
+pty, errPty
 );%0A 

support redirectErrorStream on Unix