package jetbrains.buildServer.autotools.agent;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.execution.configurations.GeneralCommandLine;
import java.util.UUID;
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.util.EventDispatcher;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.autotools.common.AutotoolsBuildConstants.*;

/**
 * Created on 26.07.2017.
 * Author     : Nadezhda Demina
 */
public class AutotoolsLifeCycleListener extends AgentLifeCycleAdapter {

  /**
   * Does autotools test report
   */
  private AutotoolsTestsReporter testReporter;
  AutotoolsLifeCycleListener(EventDispatcher<AgentLifeCycleListener> dispatcher) {
    dispatcher.addListener(this);
  }


  /**
   * Returns true if version v1 < version v2.
   * @param v1 first version
   * @param v2 second version
   * @return true if version v1 < version, v2 else false
   */
  @NotNull
  @VisibleForTesting
  static boolean compareVersions(@NotNull final String v1,@NotNull final String v2){
    final String[] v1mas = v1.split(".");
    final String[] v2mas = v2.split(".");
    for (int i = 0; i < Math.min(v1mas.length, v2mas.length); i++){
      if (Integer.parseInt(v1mas[i]) != Integer.parseInt(v2mas[i])){
        return Integer.parseInt(v1mas[i]) < Integer.parseInt(v2mas[i]);
      }
    }
    return v1mas.length < v2mas.length;
  }

  /**
   * Find runtest tool
   * @param runner BuildRunnerContext
   */
  private static void findToolRuntest(@NotNull final BuildRunnerContext runner){
    final GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath("runtest");
    commandLine.addParameter("--version");
    final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, (byte[])null);
    if (execResult.getExitCode() != 0) {
      return;
    }
    String version = "";
    for (final String line : execResult.getOutLines()) {
      if (!line.startsWith("DejaGnu version")) continue;
      Matcher matcher = Pattern.compile("\\d+(\\.\\d+)+").matcher(line);
      if (matcher.find()) {
        version = matcher.group();
      }
    }
    runner.addRunnerParameter(HAS_RUNTEST_VAR, "1");
    runner.addRunnerParameter(RUNTEST_XML_FILE_VAR, Boolean.toString(compareVersions(version, "1.6")));
  }

  @Override
  public void beforeRunnerStart(@NotNull final BuildRunnerContext runner) {
    findToolRuntest(runner);
    testReporter = new AutotoolsTestsReporter(System.currentTimeMillis(), runner.getBuild().getBuildLogger(),
                                              runner.getBuild().getCheckoutDirectory().getAbsolutePath() + "/",
                                              Boolean.parseBoolean(runner.getRunnerParameters().get(UI_NEED_DEJAGNU_VALID_XML)));
    testReporter.findDejagnu(runner.getBuild().getCheckoutDirectory());
  }



  @Override
  public void runnerFinished(@NotNull final BuildRunnerContext runner, @NotNull final BuildFinishedStatus status) {
    super.runnerFinished(runner, status);
    testReporter.searchTestsFiles(runner.getBuild().getCheckoutDirectory());
    testReporter.doTestsReport();
  }
}

@@ -974,1796 +974,200 @@
 %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  /**%0A   * Find runtest tool%0A   * @param runner BuildRunnerContext%0A   */%0A  private static void findToolRuntest(@NotNull final BuildRunnerContext runner)%7B%0A    final GeneralCommandLine commandLine = new GeneralCommandLine();%0A    commandLine.setExePath(%22runtest%22);%0A    commandLine.addParameter(%22--version%22);%0A    final ExecResult execResult = SimpleCommandLineProcessRunner.runCommand(commandLine, (byte%5B%5D)null);%0A    if (execResult.getExitCode() != 0) %7B%0A      return;%0A    %7D%0A    String version = %22%22;%0A    for (final String line : execResult.getOutLines()) %7B%0A      if (!line.startsWith(%22DejaGnu version%22)) continue;%0A      Matcher matcher = Pattern.compile(%22%5C%5Cd+(%5C%5C.%5C%5Cd+)+%22).matcher(line);%0A      if (matcher.find()) %7B%0A        version = matcher.group();%0A      %7D%0A    %7D%0A    runner.addRunnerParameter(HAS_RUNTEST_VAR, %221%22);%0A    runner.addRunnerParameter(RUNTEST_XML_FILE_VAR, Boolean.toString(compareVersions(version, %221.6%22)));%0A  %7D%0A%0A  @Override%0A  public void beforeRunnerStart(@NotNull final BuildRunnerContext runner) %7B%0A    findToolRuntest(runner);%0A    testReporter = new AutotoolsTestsReporter(System.currentTimeMillis(), runner.getBuild().getBuildLogger(),
+%7D%0A%0A  @Override%0A  public void beforeRunnerStart(@NotNull final BuildRunnerContext runner) %7B%0A    myRuntestToolProvider = (RuntestToolProvider) myProvidersRegistry.findToolProvider(TOOL_RUNTEST);
 %0A   

remove findToolRuntest and compareVersions from AutotoolsLifeCycleListener