/*
 * SonarQube
 * Copyright (C) 2009-2016 SonarSource SA
 * mailto:contact AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonarsource.sonarqube.perf.scanner.suite;

import com.google.common.base.Strings;
import com.sonar.orchestrator.Orchestrator;
import com.sonar.orchestrator.build.BuildResult;
import com.sonar.orchestrator.build.SonarScanner;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.wsclient.services.PropertyCreateQuery;
import org.sonarsource.sonarqube.perf.MavenLogs;
import org.sonarsource.sonarqube.perf.PerfRule;
import org.sonarsource.sonarqube.perf.PerfTestCase;

public class MemoryTest extends PerfTestCase {

  @Rule
  public PerfRule perfRule = new PerfRule(4) {
    @Override
    protected void beforeEachRun() {
      orchestrator.resetData();
    }
  };

  @ClassRule
  public static TemporaryFolder temp = new TemporaryFolder();

  @ClassRule
  public static Orchestrator orchestrator = ScannerPerfTestSuite.ORCHESTRATOR;

  @Before
  public void cleanDatabase() {
    orchestrator.resetData();
  }

  @Test
  public void should_not_fail_with_limited_xmx_memory_and_no_coverage_per_test() {
    orchestrator.executeBuild(
      newScanner("-Xmx80m -server -XX:-HeapDumpOnOutOfMemoryError"));
  }

  int DEPTH = 4;

  // Property on root module is duplicated in each module so it may be big
  @Test
  public void analyzeProjectWithManyModulesAndBigProperties() throws IOException {

    File baseDir = temp.newFolder();

    prepareModule(baseDir, "moduleA", 1);
    prepareModule(baseDir, "moduleB", 1);
    prepareModule(baseDir, "moduleC", 1);

    FileUtils.write(new File(baseDir, "sonar-project.properties"), "sonar.modules=moduleA,moduleB,moduleC\n", true);
    FileUtils.write(new File(baseDir, "sonar-project.properties"), "sonar.myBigProp=" + Strings.repeat("A", 10000), true);

    SonarScanner scanner = SonarScanner.create()
      .setProperties(
        "sonar.projectKey", "big-module-tree",
        "sonar.projectName", "Big Module Tree",
        "sonar.projectVersion", "1.0",
        "sonar.sources", "",
        "sonar.showProfiling", "true");
    scanner.setEnvironmentVariable("SONAR_RUNNER_OPTS", "-Xmx512m -server")
      .setProjectDir(baseDir);

    BuildResult result = orchestrator.executeBuild(scanner);
    perfRule.assertDurationAround(MavenLogs.extractTotalTime(result.getLogs()), 4480L);

    // Second execution with a property on server side
    orchestrator.getServer().getAdminWsClient().create(new PropertyCreateQuery("sonar.anotherBigProp", Strings.repeat("B", 1000), "big-module-tree"));
    result = orchestrator.executeBuild(scanner);
    perfRule.assertDurationAround(MavenLogs.extractTotalTime(result.getLogs()), 4420L);
  }

  private void prepareModule(File parentDir, String moduleName, int depth) throws IOException {
    File moduleDir = new File(parentDir, moduleName);
    moduleDir.mkdir();
    File projectProps = new File(moduleDir, "sonar-project.properties");
    FileUtils.write(projectProps, "sonar.moduleKey=" + moduleName + "\n", true);
    if (depth < DEPTH) {
      FileUtils.write(projectProps, "sonar.modules=" + moduleName + "A," + moduleName + "B," + moduleName + "C\n", true);
      prepareModule(moduleDir, moduleName + "A", depth + 1);
      prepareModule(moduleDir, moduleName + "B", depth + 1);
      prepareModule(moduleDir, moduleName + "C", depth + 1);
    }
  }

}
