package jetbrains.buildServer.autotools.agent;

import com.google.common.annotations.VisibleForTesting;
import com.intellij.execution.configurations.GeneralCommandLine;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
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
   */

  protected final static String regVersionNumer = "\\d+(?:\\.\\d+)+";
  protected String myVersion;
  protected final String myToolName;
  protected final String myVersionArg;

  @VisibleForTesting
  public AutotoolsToolProvider(@NotNull String toolName, @NotNull String versionArg){
    myToolName = toolName;
    myVersionArg = versionArg;
  }

  public AutotoolsToolProvider(@NotNull ToolProvidersRegistry toolProvidersRegistry,
                               @NotNull EventDispatcher<AgentLifeCycleListener> eventDispatcher,@NotNull String toolName, @NotNull String versionArg){
    toolProvidersRegistry.registerToolProvider(this);
    eventDispatcher.addListener(this);
    myVersionArg = versionArg;
    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(myVersionArg);
    final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, (byte[])null);
    if (execResult.getExitCode() == 0){
      myVersion = findVersion(execResult.getOutLines().toString());
    }
    return execResult.getExitCode() == 0;
  }

  @NotNull
  @VisibleForTesting
  String findVersion(@NotNull final String text) {
    final Pattern p = Pattern.compile(regVersionNumer);
    final Matcher matcher = p.matcher(text);
    return matcher.find() ? text.substring(matcher.start(), matcher.end()) : "";
  }
  @NotNull
  public String getVersion(){
    return myVersion;
  }

  @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;
  }
}

@@ -1034,16 +1034,662 @@
 g;%0A  %7D%0A%0A
+  /**%0A   * Returns true if version v1 %3C= version v2.%0A   * @param v1 first version%0A   * @param v2 second version%0A   * @return true if version v1 %3C= version, v2 else false%0A   */%0A  @NotNull%0A  @VisibleForTesting%0A  static boolean compareVersions(@NotNull final String v1,@NotNull final String v2)%7B%0A    final String%5B%5D v1mas = v1.split(%22.%22);%0A    final String%5B%5D v2mas = v2.split(%22.%22);%0A    for (int i = 0; i %3C Math.min(v1mas.length, v2mas.length); i++)%7B%0A      if (Integer.parseInt(v1mas%5Bi%5D) != Integer.parseInt(v2mas%5Bi%5D))%7B%0A        return Integer.parseInt(v1mas%5Bi%5D) %3C Integer.parseInt(v2mas%5Bi%5D);%0A      %7D%0A    %7D%0A    return v1mas.length %3C= v2mas.length;%0A  %7D%0A%0A
   public
@@ -1765,16 +1765,16 @@
 gistry,%0A
-
         
@@ -2467,17 +2467,505 @@
 );%0A  %7D%0A%0A
+  /**%0A   * Returns string from string array with splitter '%5Cn'%0A   * @param strArr array of strings%0A   * @return string joined of strArr%0A   */%0A  @NotNull%0A  @VisibleForTesting%0A  static String stringArrayToString(String%5B%5D strArr)%7B%0A    if (strArr.length == 0) return %22%22;%0A    StringBuilder result = new StringBuilder();%0A    result.append(strArr%5B0%5D);%0A    for (int i = 1; i %3C strArr.length; i++)%7B%0A      result.append('%5Cn');%0A      result.append(strArr%5Bi%5D);%0A    %7D%0A    return result.toString();%0A  %7D
 %0A
-
   /**%0A  
@@ -3389,16 +3389,36 @@
 Version(
+stringArrayToString(
 execResu
@@ -3433,26 +3433,16 @@
 tLines()
-.toString(
 ));%0A    
@@ -3899,24 +3899,24 @@
 String s) %7B%0A
-
     return m
@@ -3934,16 +3934,35 @@
 quals(s)
+ && isExistedTool()
 ;%0A  %7D%0A%0A 

add funtion stringArrayToString in AutotoolsToolProvider