package org.jenkinsci.plugins.gitclient;

import hudson.EnvVars;
import hudson.Extension;
import hudson.Functions;
import hudson.init.Initializer;
import hudson.model.EnvironmentSpecific;
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 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();
    }

    @Initializer(before=PLUGINS_STARTED)
    public static void addAliases() {
        Jenkins.XSTREAM2.addCompatibilityAlias("hudons.plugins.git.GitTool", 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.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();
    }

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


    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);
    }

    @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;
                }
            }
            return null;
        }
    }

}


@@ -104,24 +104,47 @@
 .Functions;%0A
+import hudson.XmlFile;%0A
 import hudso
@@ -159,24 +159,24 @@
 nitializer;%0A
-
 import hudso
@@ -779,16 +779,81 @@
 il.List;
+%0Aimport java.util.logging.Level;%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -1393,188 +1393,8 @@
  %7D%0A%0A
-    @Initializer(before=PLUGINS_STARTED)%0A    public static void addAliases() %7B%0A        Jenkins.XSTREAM2.addCompatibilityAlias(%22hudons.plugins.git.GitTool%22, GitTool.class);%0A    %7D%0A%0A%0A
     
@@ -3148,24 +3148,472 @@
    super();%0A
+            File legacy = new File(Jenkins.getInstance().getRootDir(), %22hudson.plugins.git.GitTool.xml%22);%0A            if (legacy.exists()) %7B%0A                try %7B%0A                    new XmlFile(legacy).unmarshal(this);%0A                    save();%0A                    legacy.delete();%0A                %7D catch (IOException e) %7B%0A                    LOGGER.log(Level.WARNING, %22Failed to load %22 + legacy, e);%0A                %7D%0A            %7D else %7B%0A    
             
@@ -3616,24 +3616,38 @@
     load();%0A
+            %7D%0A
         %7D%0A%0A 
@@ -4512,11 +4512,95 @@
 %0A    %7D%0A%0A
+    private static final Logger LOGGER = Logger.getLogger(GitTool.class.getName());%0A
 %7D%0A%0A

load legacy hudson.plugins.git.GitTool.xml file for backward compatibility