package net.dzikoysk.funnyguilds.creator;

import net.dzikoysk.funnyguilds.creator.utils.AlertUtils;
import net.dzikoysk.funnyguilds.creator.utils.JdkUtils;
import net.dzikoysk.funnyguilds.creator.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.apache.maven.shared.invoker.*;
import org.codehaus.plexus.util.ExceptionUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class FunnyMaven {

    private final FunnyCreator funnyCreator;
    private Invoker invoker;
    private Element projectElement;

    public FunnyMaven(FunnyCreator funnyCreator) {
        this.funnyCreator = funnyCreator;
    }

    public void prepare() throws Exception {
        this.funnyCreator.info("Extracting maven");
        ZipUtils.unzipResource("/apache-maven-3.5.0.zip", FunnyConstants.MAVEN_DIRECTORY.getPath());

        this.invoker = new DefaultInvoker();
        this.invoker.setMavenHome(FunnyConstants.MAVEN_DIRECTORY);

        if (!FunnyConstants.BUILD_DIRECTORY.exists()) {
            FileUtils.forceMkdir(FunnyConstants.BUILD_DIRECTORY);
        }

        FunnyCreator.getLogger().info("Parse pom.xml");

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(new File(FunnyConstants.REPOSITORY_DIRECTORY, "pom.xml"));
        doc.getDocumentElement().normalize();

        this.projectElement = (Element) doc.getElementsByTagName("project").item(0);
    }

    public void build() throws Exception {
        this.funnyCreator.info("Building repository");

        String[] goals = new String[] {
                "-f " + FunnyConstants.REPOSITORY_DIRECTORY.getPath(),
                "-DoutputDirectory=" + FunnyConstants.BUILD_DIRECTORY.getPath() };

        InvocationRequest request = new DefaultInvocationRequest();
        request.setGoals(Arrays.asList(goals));
        request.setJavaHome(JdkUtils.find());

        InvocationResult result = invoker.execute(request);

        if (result.getExitCode() != 0) {
            FunnyCreator.getLogger().info("Something went wrong");
            Exception exception = result.getExecutionException();

            if (exception != null) {
                AlertUtils.alert("FunnyCreator Exception", exception.getMessage(), ExceptionUtils.getStackTrace(exception), funnyCreator::shutdown);
            }
            else {
                AlertUtils.alert("FunnyCreator Exception", "[Build] Wynik: " + result.getExitCode(), "Prawdopodobnie aplikacja nie została uruchomiona przy użyciu JDK8", funnyCreator::shutdown);
            }

            return;
        }

        FunnyCreator.getLogger().info("Maven Result: Done");
    }

    public void moveOutput() throws IOException {
        String version = getVersion();
        funnyCreator.info("Preparing output (FunnyGuilds " + version + ")");

        File source = new File(FunnyConstants.REPOSITORY_DIRECTORY + "/target", "funnyguilds-" + version + ".jar");
        File target = new File(FunnyConstants.BUILD_DIRECTORY, "funnyguilds-indev-" + version + ".jar");

        FileUtils.copyFile(source, target);
    }

    public String getVersion() {
        return projectElement.getElementsByTagName("version").item(0).getTextContent();
    }

}