package com.coravy.hudson.plugins.github;

import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Job;
import hudson.model.JobProperty;
import hudson.model.JobPropertyDescriptor;
import net.sf.json.JSONObject;

import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;

/**
 * Stores the github related project properties.
 * <p>
 * As of now this is only the URL to the github project.
 * 
 * @todo Should we store the GithubUrl instead of the String?
 * @author Stefan Saasen <stefan@coravy.com>
 */
public final class GithubProjectProperty extends
        JobProperty<AbstractProject<?, ?>> {

    /**
     * This will the URL to the project main branch.
     */
    private String projectUrl;

    @DataBoundConstructor
    public GithubProjectProperty(String projectUrl) {
        this.projectUrl = new GithubUrl(projectUrl).baseUrl();
    }

    /**
     * @return the projectUrl
     */
    public GithubUrl getProjectUrl() {
        return new GithubUrl(projectUrl);
    }

    @Override
    public Action getJobAction(AbstractProject<?, ?> job) {
        if (null != projectUrl) {
            return new GithubLinkAction(this);
        }
        return null;
    }
    /*
    @Override
    public JobPropertyDescriptor getDescriptor() {
        return DESCRIPTOR;
    }

    public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
    */
    @Extension
    public static final class DescriptorImpl extends JobPropertyDescriptor {

        public DescriptorImpl() {
            super(GithubProjectProperty.class);
            load();
        }

        public boolean isApplicable(Class<? extends Job> jobType) {
            return AbstractProject.class.isAssignableFrom(jobType);
        }

        public String getDisplayName() {
            return "Github project page";
        }

        @Override
        public JobProperty<?> newInstance(StaplerRequest req,
                JSONObject formData) throws FormException {
            GithubProjectProperty tpp = req.bindJSON(
                    GithubProjectProperty.class, formData);
            if (tpp.projectUrl == null) {
                tpp = null; // not configured
            }
            return tpp;
        }

    }
}

@@ -223,24 +223,83 @@
 Descriptor;%0A
+import java.util.Collection;%0Aimport java.util.Collections;%0A
 import net.s
@@ -1148,22 +1148,44 @@
  public 
+Collection%3C? extends 
 Action
+%3E
  getJobA
@@ -1189,16 +1189,17 @@
 obAction
+s
 (Abstrac
@@ -1265,32 +1265,54 @@
          return 
+Collections.singleton(
 new GithubLinkAc
@@ -1321,16 +1321,17 @@
 on(this)
+)
 ;%0A      
@@ -1349,20 +1349,39 @@
  return 
-null
+Collections.emptyList()
 ;%0A    %7D%0A

update impl of deprecated API