import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import uws.UWSException;
import uws.job.ErrorType;
import uws.job.JobList;
import uws.job.JobThread;
import uws.job.UWSJob;
import uws.job.parameters.InputParamController;
import uws.job.parameters.NumericParamController;
import uws.job.parameters.StringParamController;
import uws.job.user.JobOwner;
import uws.service.UWSServlet;
import uws.service.UWSUrl;

public class UWSMCutout extends UWSServlet {
   private static final long serialVersionUID = 1L;

   protected static final Settings    settings   = Settings.getInstance();
   protected static final Subsurvey[] subsurveys = Subsurvey.loadSubsurveys(
         settings.fitsPaths.surveysMetadataAbsPathname());

   /* REQUIRED
    * Initialize your UWS. At least, you should create one jobs list. */
   @Override
   public void initUWS() throws UWSException
   {
      addJobList(new JobList("mcutout"));
      UWSMCutoutUserIdentifier uwsUserIdentifier = new UWSMCutoutUserIdentifier();
      setUserIdentifier(uwsUserIdentifier);
   }

   /*
    * REQUIRED
    * Create instances of jobs, but only the "work" part. The "work" and the description of the job (and all the provided parameters)
    * are now separated and only kept in the UWSJob given in parameter. This one is created automatically by the API.
    * You just have to provide the "work" part.
    */
   @Override
   public JobThread createJobThread(UWSJob job) throws UWSException{
      if (job.getJobList().getName().equals("mcutout")) // FIXME listanme to Config-file ?
         return new UWSMCutoutWork(job);
      else
         throw new UWSException("Impossible to create a job inside the jobs list \"" + job.getJobList().getName() + "\" !");
   }

   /* OPTIONAL
    * By overriding this function, you can customize the root of your UWS.
    * If this function is not overridden an XML document which lists all registered jobs lists is returned. */
   @Override
   protected void writeHomePage(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{
      PrintWriter out = resp.getWriter();

      out.println("<html><head><title>VLKB Multi-Cutout service</title></head><body>");
      out.println("<h1>VLKB MCutout service</h1");
      out.println("<p>Available job lists:</p>");

      out.println("<ul>");
      for(JobList jl : this){
         out.println("<li>" + jl.getName() + " - " + jl.getNbJobs() + " jobs - <a href=\"" + requestUrl.listJobs(jl.getName()) + "\">" + requestUrl.listJobs(jl.getName()) + "</a></li>");
      }
      out.println("</ul>");
   }

}
