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 RESPONSE_ENCODING = "utf-8";

   private Settings     settings  = UWSMCutout.settings;
   private Subsurvey[] subsurveys = UWSMCutout.subsurveys;

   protected Vlkb vlkb = (settings.amqpConn.isHostnameEmpty() ?
         new VlkbCli(settings, subsurveys)
         : new VlkbAmqp(settings, subsurveys));

   /* 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 */

            MCutResult mresult = vlkb.doMCutout(reqJsonString);

            /* Implement -> SODA */

            PrintWriter writer = new PrintWriter(new OutputStreamWriter(respOutputStream, RESPONSE_ENCODING));

            String accessUrl = convertLocalPathnameToRemoteUrl(mresult.fileName,
                  settings.fitsPaths.cutouts(),
                  settings.fitsPaths.cutoutsUrl());

            XmlSerializer.serializeToLegacyCutResult(writer, RESPONSE_ENCODING,
                  mresult, accessUrl,
                  //id, pos, band, time, pol, pixels, countNullValues,
                  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());
      }
   }

   private String convertLocalPathnameToRemoteUrl(String localPathname,
         String FITScutpath, String FITSRemoteUrlCutouts)
   {
      //LOGGER.info("trace " + localPathname);
      String fileName = localPathname.replaceAll(FITScutpath + "/", "");
      //LOGGER.info("local filename: " + fileName);
      String remotefname = FITSRemoteUrlCutouts + "/" + fileName;
      //LOGGER.info("remote url    : " + remotefname);
      return remotefname;
   }


}
