package com.github.cseppento.gradle.evosuite;

import com.github.cseppento.gradle.evosuite.internal.DefaultEvoSuiteExtension;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.logging.Logger;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.*;
import org.gradle.api.tasks.testing.Test;

import java.util.Objects;

/**
 * This plugin integrates EvoSuite test generation and execution with Gradle.
 */
public class EvoSuitePlugin implements Plugin<Project> {
    private static final String DEFAULT_TOOL_VERSION = "1.0.5";

    private static final String EXTENSION_NAME = "evosuite";
    private static final String TEST_GENERATION_CONFIG_NAME = "evosuiteGeneration";
    private static final String SOURCE_SET_NAME = "evosuiteTest";
    private static final String SOURCE_SET_DIR_NAME = "evoTest";

    private Project project;
    private Logger logger;
    private TaskContainer tasks;
    private SourceSetContainer sourceSets;

    private EvoSuiteExtension extension;
    private Configuration evosuiteGenerateConfig;

    private SourceSet sourceSet;

    @Override
    public void apply(Project project) {
        Objects.requireNonNull(project);
        this.project = project;
        this.logger = project.getLogger();
        this.tasks = project.getTasks();

        if (project.getExtensions().findByName(EXTENSION_NAME) != null) {
            logger.info("The {] extension has been already applied", EXTENSION_NAME);
            return;
        }
        if (project.getPluginManager().findPlugin("java") == null) {
            throw new GradleException("Please apply the java plugin first in order to use the EvoSuite plugin");
        }

        this.sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();

        extension = project.getExtensions().create(
                EvoSuiteExtension.class, EXTENSION_NAME, DefaultEvoSuiteExtension.class,
                project, DEFAULT_TOOL_VERSION);

        evosuiteGenerateConfig = project.getConfigurations().create(TEST_GENERATION_CONFIG_NAME);
        evosuiteGenerateConfig.defaultDependencies(depSet -> {
            depSet.add(project.getDependencies().create("org.evosuite:evosuite-master:" + extension.getToolVersion()));
        });

        createSourceSet();

        createTasks();

        project.getConfigurations().getByName(sourceSet.getCompileConfigurationName()).defaultDependencies(depSet -> {
            depSet.add(project.getDependencies().create("org.evosuite:evosuite-client:" + extension.getToolVersion()));
        });

        // TODO detect IDE plugins (even if applied later) and add sourceSet to IDE config
    }

    private void createSourceSet() {
        sourceSet = sourceSets.create(SOURCE_SET_NAME);

        sourceSet.getJava().setSrcDirs(project.files(String.format("src/%s/java", SOURCE_SET_DIR_NAME)));
        sourceSet.getResources().setSrcDirs(project.files(String.format("src/%s/resources", SOURCE_SET_DIR_NAME)));

        SourceSetOutput mainOutput = sourceSets.getByName("main").getOutput();
        sourceSet.setCompileClasspath(project.files(sourceSet.getCompileClasspath(), mainOutput));
        sourceSet.setRuntimeClasspath(project.files(sourceSet.getRuntimeClasspath(), mainOutput));
    }

    private void createTasks() {
        // TODO task evosuiteListClasses
        // TODO task evosuiteHelp
        // TODO task evosuiteParameters

        // Task: evosuiteGenerateTests : JavaExec
        JavaExec genTask = tasks.create("evosuiteGenerateTests", JavaExec.class);
        genTask.dependsOn(tasks.getByName("classes"));
        genTask.setClasspath(evosuiteGenerateConfig);
        genTask.setMain("org.evosuite.EvoSuite");

        String projectClasspath = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME).getOutput().getClassesDirs().getAsPath();
        genTask.args("-target", projectClasspath,
                "-projectCP", projectClasspath,
                "-generateSuite",
                "-Dtest_dir=" + sourceSet.getJava().getSrcDirs().iterator().next()
        );

        // Task: evosuiteTest : Test
        Test evosuiteTest = tasks.create("evosuiteTest", Test.class);
        evosuiteTest.setGroup("EvoSuite");
        evosuiteTest.setDescription("Runs the tests generated by EvoSuite.");

        evosuiteTest.setTestClassesDirs(sourceSet.getOutput().getClassesDirs());
        evosuiteTest.setClasspath(sourceSet.getRuntimeClasspath());

        evosuiteTest.mustRunAfter(tasks.getByName("test"));

        tasks.getByName("check").dependsOn(evosuiteTest);
    }
}

@@ -3663,32 +3663,137 @@
 avaExec.class);%0A
+        genTask.setGroup(%22EvoSuite%22);%0A        genTask.setDescription(%22Generates tests using EvoSuite.%22);%0A
         genTask.

Add group and description to evosuiteGenerateTests task