
import java.io.FileNotFoundException;
import java.io.IOException;
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.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.io.FileUtils;

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;

import uws.service.log.UWSLog;
import uws.service.log.UWSLog.LogLevel;

// 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 = new VlkbCli(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
   {
		UWSLog logger = job.getLogger();

      try
      {
         long startTime_msec = System.currentTimeMillis();
         boolean showDuration = true;

         logger.logThread(LogLevel.INFO, this, "", "Job started",null);

         Object obj = job.getAdditionalParameterValue("mcutout");
			if(obj instanceof UploadFile)
			{
			   logger.logThread(LogLevel.INFO, this, "", "mcutout is UploadFile", null);

				UploadFile jsonFile = (UploadFile)obj;
				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();

				String workDir = settings.fitsPaths.cutouts() + "/" + job.getJobId();
				FileUtils.forceMkdir(new File(workDir));

				MCutResult mresult = vlkb.doMCutout(reqJsonString, workDir);

				logger.logThread(LogLevel.INFO, this, "Prepare Result",
						" job:requestUrl: " +  job.getUrl().getRequestURL(), null);

				publishOnEndpoint("Report", "application/json", mresult.resJsonPathname);
				publishOnEndpoint("mcutout.tar.gz", "application/gzip", mresult.fileName);

				FileUtils.deleteDirectory(new File(workDir));
			}
			else
			{
			     logger.logThread(LogLevel.INFO, this, "",
               "mcutout is NOT UploadFile type: wrong argument ? Nothing to do, exiting..."
               , null);
			}

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


	private void publishOnEndpoint(String epName, String mimeType, String absPathname)
		throws FileNotFoundException, IOException, UWSException
		{
			Result result = new Result(epName, "none", null, false);
			result.setMimeType(mimeType);

			File downloadFile = new File(absPathname);
			try(FileInputStream fileInput = new FileInputStream(downloadFile);
					OutputStream resOutputStream = getResultOutput(result))
			{
				fileInput.transferTo(resOutputStream);
				publishResult(result);
			}
			downloadFile.delete();
		}

}
