package hudson.plugins.git;

import hudson.EnvVars;
import hudson.Extension;
import hudson.Functions;
import hudson.XmlFile;
import hudson.init.Initializer;
import hudson.model.EnvironmentSpecific;
import hudson.model.Items;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.slaves.NodeSpecific;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolProperty;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;

import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import static hudson.init.InitMilestone.PLUGINS_STARTED;

/**
 * Information about Git installation.
 *
 * @author Jyrki Puttonen
 */
public final class GitTool extends ToolInstallation implements NodeSpecific<GitTool>, EnvironmentSpecific<GitTool> {

    @DataBoundConstructor
    public GitTool(String name, String home, List<? extends ToolProperty<?>> properties) {
        super(name, home, properties);
    }

    public static transient final String DEFAULT = "Default";

    public String getGitExe() {
        return getHome();
    }

    private static GitTool[] getInstallations(DescriptorImpl descriptor) {
        GitTool[] installations = null;
        try {
            installations = descriptor.getInstallations();
        } catch (NullPointerException e) {
            installations = new GitTool[0];
        }
        return installations;
    }

    public static GitTool getDefaultInstallation() {
        DescriptorImpl gitTools = Jenkins.getInstance().getDescriptorByType(GitTool.DescriptorImpl.class);
        GitTool[] installations = gitTools.getInstallations();
        if (installations.length == 1) return installations[0];
        return gitTools.getInstallation(GitTool.DEFAULT);
    }

    public GitTool forNode(Node node, TaskListener log) throws IOException, InterruptedException {
        return new GitTool(getName(), translateFor(node, log), Collections.<ToolProperty<?>>emptyList());
    }

    public GitTool forEnvironment(EnvVars environment) {
        return new GitTool(getName(), environment.expand(getHome()), Collections.<ToolProperty<?>>emptyList());
    }

    @Override
    public DescriptorImpl getDescriptor() {
        return (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitTool.class);
    }

    @Initializer(after=PLUGINS_STARTED)
    public static void onLoaded() {
        //Creates default tool installation if needed. Uses "git" or migrates data from previous versions

        DescriptorImpl descriptor = (DescriptorImpl) Jenkins.getInstance().getDescriptor(GitTool.class);
        GitTool[] installations = getInstallations(descriptor);

        if (installations != null && installations.length > 0) {
            //No need to initialize if there's already something
            return;
        }

        String defaultGitExe = Functions.isWindows() ? "git.exe" : "git";
        GitTool tool = new GitTool(DEFAULT, defaultGitExe, Collections.<ToolProperty<?>>emptyList());
        descriptor.setInstallations(new GitTool[] { tool });
        descriptor.save();
    }

    @Extension
    public static class DescriptorImpl extends ToolDescriptor<GitTool> {

        public DescriptorImpl() {
            super();
            load();
        }

        @Override
        public String getDisplayName() {
            return "Git";
        }

        @Override
        public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
            super.configure(req, json);
            save();
            return true;
        }

        public FormValidation doCheckHome(@QueryParameter File value)
            throws IOException, ServletException {

            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            String path = value.getPath();

            return FormValidation.validateExecutable(path);

        }

        public GitTool getInstallation(String name) {
            for(GitTool i : getInstallations()) {
                if(i.getName().equals(name)) {
                    return i;
                }
            }
            LOGGER.warning("invalid gitTool selection " + name + ", using default Git installation");
            return GitTool.getDefaultInstallation();
        }
    }

    private static final Logger LOGGER = Logger.getLogger(GitTool.class.getName());
}


@@ -99,31 +99,8 @@
 ns;%0A
-import hudson.XmlFile;%0A
 impo
@@ -123,24 +123,24 @@
 nitializer;%0A
+
 import hudso
@@ -172,35 +172,8 @@
 ic;%0A
-import hudson.model.Items;%0A
 impo
@@ -748,40 +748,8 @@
 st;%0A
-import java.util.logging.Level;%0A
 impo
@@ -1818,32 +1818,21 @@
  GitTool
-%5B%5D installations
+ tool
  = gitTo
@@ -1854,91 +1854,65 @@
 tion
-s();%0A        if (installations.length == 1) return installations%5B0%5D;%0A        return
+(GitTool.DEFAULT);%0A        return (tool != null) ? tool :
  git
@@ -1932,33 +1932,22 @@
 allation
-(GitTool.DEFAULT)
+s()%5B0%5D
 ;%0A    %7D%0A
@@ -3258,31 +3258,32 @@
 tor.save();%0A
-
     %7D%0A%0A
+%0A
     @Extensi

use first installation as "default" if no explicit "Default" one exists