import java.io.File;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import uws.UWSException;
import uws.job.ErrorType;
import uws.job.JobThread;
import uws.job.user.JobOwner;
import uws.job.user.DefaultJobOwner;
import uws.job.Result;
import uws.job.UWSJob;
import uws.job.jobInfo.JobInfo;
import uws.job.jobInfo.XMLJobInfo;
import uws.job.jobInfo.SingleValueJobInfo;

import uws.service.request.UploadFile;
import uws.service.file.LocalUWSFileManager;
import uws.service.file.UWSFileManager;
import uws.service.UWSUrl;

// rbu
import java.util.*; 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;



public class UWSMCutoutWork extends JobThread
{
   final String RESP_ENCODING = "utf-8";

   private Settings settings = UWSMCutout.settings;

   protected Datasets datasets = new DatasetsImpl(settings);

   /* NOTE needed if cutouts dir served by vlkb-datasets */
   private String webappRootRequestUrl = null;

   public UWSMCutoutWork(UWSJob j) throws UWSException{
      super(j);
     UWSUrl url = j.getUrl();
     webappRootRequestUrl = url.getUrlHeader();
   }



   @Override
   protected void jobWork() throws UWSException, InterruptedException
   {
      try
      {
         long startTime_msec = System.currentTimeMillis();
         boolean showDuration = true;

         /* UWS -> SODA (JDL in POST body is part of SODA REC) */

         UploadFile jsonFile = (UploadFile)job.getAdditionalParameterValue("mcutout");
         final String contentType = "text/xml"; // FIXME should be input param ? RESPONSEFORMAT ?

         Result result = createResult("Report");
         result.setMimeType("text/xml");
         OutputStream respOutputStream = getResultOutput(result);

         if(contentType.equals("text/xml") || contentType.equals("application/xml"))
         {
            InputStreamReader isr = new InputStreamReader(jsonFile.open());
            BufferedReader input = new BufferedReader(isr);
            StringBuffer jsonStringBuffer = new StringBuffer();
            String line;
            while((line = input.readLine()) != null)
            {
               jsonStringBuffer.append(line);
            }
            String reqJsonString = jsonStringBuffer.toString();

            /* SODA -> Implementation */

            DataLink dlk = datasets.doMCutout(reqJsonString);

            /* Implement -> SODA */

            PrintWriter writer = new PrintWriter(new OutputStreamWriter(respOutputStream, RESP_ENCODING));
            XmlSerializer.serializeToLegacyCutResults(writer, RESP_ENCODING, dlk, showDuration, startTime_msec);
            writer.close();

            /* SODA -> UWS */
         }
         else
         {
            throw new AssertionError("Unsupported contentType for output: " + contentType);
         }

         /* FIXME here was uws-check is-job-Interrupted */

         publishResult(result);
      }
      catch(IOException ex)
      {
         throw new UWSException("Internal error: jsonFile.open() throws IOException:" + ex.getMessage());
      }
   }

}
