package jetbrains.buildServer.autotools.agent;

import com.intellij.execution.configurations.GeneralCommandLine;
import jetbrains.buildServer.ExecResult;
import jetbrains.buildServer.SimpleCommandLineProcessRunner;
import jetbrains.buildServer.agent.*;
import jetbrains.buildServer.log.Loggers;
import jetbrains.buildServer.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;

/**
 * Created on 10.08.2017.
 * Author     : Nadezhda Demina
 */
public class AutotoolsToolProvider extends AgentLifeCycleAdapter implements ToolProvider {
  /**
   * Tool Name
   */
  private final String myToolName;
  public AutotoolsToolProvider(ToolProvidersRegistry toolProvidersRegistry,
                               EventDispatcher<AgentLifeCycleListener> eventDispatcher, String toolName){
    toolProvidersRegistry.registerToolProvider(this);
    eventDispatcher.addListener(this);
    myToolName = toolName;
  }


  @Override
  public void beforeAgentConfigurationLoaded(@NotNull BuildAgent agent) {
    if (isExistedTool()){
      Loggers.AGENT.info("AutotoolsToolProvider for tool " + myToolName + " found");
      agent.getConfiguration().addConfigurationParameter(myToolName, myToolName);
      return;
    }

    Loggers.AGENT.info("AutotoolsToolProvider for tool " + myToolName + "did not find");
  }


  /**
   * Returns True if Existed Tool myConfigName
   * @return
   */
  public boolean isExistedTool(){
    final GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(myToolName);
    commandLine.addParameter("--version");
    final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, (byte[])null);
    return execResult.getExitCode() == 0;
  }

  @NotNull
  @Override
  public boolean supports(@NotNull final String s) {
    return myToolName.equals(s);
  }

  @NotNull
  @Override
  public String getPath(@NotNull final String s) throws ToolCannotBeFoundException {
    return myToolName;
  }

  @NotNull
  @Override
  public String getPath(@NotNull final String s, @NotNull final AgentRunningBuild agentRunningBuild, @NotNull final BuildRunnerContext buildRunnerContext) throws ToolCannotBeFoundException {
    return myToolName;
  }
}

@@ -570,17 +570,20 @@
  */%0A
+%0A
   pr
-iva
+otec
 te
+d
  fin
@@ -604,16 +604,56 @@
 olName;%0A
+  protected final String myVersionArg;%0A%0A
   public
@@ -675,16 +675,25 @@
 rovider(
+@NotNull 
 ToolProv
@@ -760,16 +760,25 @@
         
+@NotNull 
 EventDis
@@ -825,16 +825,24 @@
 patcher,
+@NotNull
  String 
@@ -849,16 +849,44 @@
 toolName
+, @NotNull String versionArg
 )%7B%0A    t
@@ -969,24 +969,55 @@
 ener(this);%0A
+    myVersionArg = versionArg;%0A
     myToolNa
@@ -1680,19 +1680,20 @@
 ter(
-%22--v
+myV
 ersion
-%22
+Arg
 );%0A 
@@ -1838,24 +1838,25 @@
  == 0;%0A  %7D%0A%0A
+%0A
   @NotNull%0A 

add myVersionArg in AutotoolsToolProvider