import java.io.File;
import java.io.FileInputStream;
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;



public class UWSMCutoutWork extends JobThread
{

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

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

         final String contentType = "application/gzip";// FIXME force stream output

         if(contentType.equals("text/xml") || contentType.equals("application/xml"))
         {
            Result result = createResult("Report");
            result.setMimeType("text/xml");
            OutputStream respOutputStream = getResultOutput(result);
            final String RESPONSE_ENCODING = "utf-8";

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

            publishResult(result);
         }
         else if(contentType.equals("application/gzip") || contentType.equals("application/x-tar+gzip"))
         {
            Result result = createResult("mcutout.tar.gz");
            result.setMimeType("application/gzip");
            OutputStream respOutputStream = getResultOutput(result);

            String absCutPathname = mresult.fileName;
            File downloadFile = new File(absCutPathname);
            FileInputStream fileInput = new FileInputStream(downloadFile);

            fileInput.transferTo(respOutputStream);

            downloadFile.delete();
            mresult.deleteCutFiles();

            publishResult(result);
         }
         else
         {
            throw new AssertionError("Unsupported contentType for output: " + contentType);
         }

         /* FIXME here was uws-check is-job-Interrupted */
      }
      catch(IOException ex)
      {
         throw new UWSException("Internal error: jsonFile.open() throws IOException:" + ex.getMessage());
      }
   }

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


}
