
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.util.Map;

import uws.UWSException;

import uws.job.AbstractJob;
import uws.job.ErrorType;
import uws.job.Result;

/**
 * A simple Timer. Its execution task is: to wait the given time (expressed in number of seconds).
 */
public class JobChrono extends AbstractJob {
	private static final long serialVersionUID = 1L;
	
	protected int time = 0;
	protected static String resultsDir = null;
	
	
	public JobChrono(Map<String, String> lstParam) throws UWSException {
		super(lstParam);
	}
	
	public static final String getResultDirectory(){
		return resultsDir;
	}
	
	public static final void setResultDirectory(String directoryPath){
		if (resultsDir == null)
			resultsDir = directoryPath;
	}

	@Override
	protected boolean loadAdditionalParams() throws UWSException {
		System.out.println("Path: "+(new File(".")).getAbsolutePath());
		// JobChrono needs only one parameter for its execution: the time:
		if (additionalParameters.containsKey("time")){
			try{
				time = Integer.parseInt(additionalParameters.get("time"));
				if (time < 0){
					time = 0;
					additionalParameters.put("time", "0");
				}
				// If you want you can remove this parameter from the map additionalParameters:
				// additionalParameters.remove("time");
				setQuote(time);
			}catch(NumberFormatException nfe){
				throw new UWSException(UWSException.BAD_REQUEST, "The given TIME value (\""+additionalParameters.get("time")+"\") is incorrect: it must be a positive integer value !");
			}
		}
		
		return true;
	}

	@Override
	protected void jobWork() throws UWSException, InterruptedException {
		int count = 0;
		// 1. EXECUTION TASK = to wait {time} seconds:
		while(!thread.isInterrupted() && count < time){
			Thread.sleep(1000);
			count++;
		}
		
		// If the task has been canceled/interrupted, throw the corresponding exception:
		if (thread.isInterrupted())
			throw new InterruptedException();

		// 2. WRITE THE RESULT FILE:
		String fileName = "JobChrono_n"+getJobId()+"_result.txt";
		File f = new File(resultsDir, fileName);
		
		try {
			// Build the directory if not existing:
			if (!f.getParentFile().exists())
				f.getParentFile().mkdirs();
			
			// Write the result:
			BufferedWriter writer = new BufferedWriter(new FileWriter(f));
			writer.write(time+" seconds elapsed");
			writer.close();
			
			// Add it to the results list of this job:
			addResult(new Result("Report", "Info", "/uwstuto/jobResults/"+fileName));
			
		} catch (IOException e) {
			// If there is an error, encapsulate it in an UWSException so that an error summary can be published:
			throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, e, "Impossible to write the result file at \""+f.getAbsolutePath()+"\" !", ErrorType.TRANSIENT);
		}
	}

	@Override
	public void clearResources() {
		// 1. STOP THE JOB (if running):
		super.clearResources();
		
		// 2. DELETE THE RESULT FILE (if any):
		try {
			File f = new File(resultsDir+"JobChrono_n"+getJobId()+"_result.txt");
			if (f.exists() && f.canWrite())
				f.delete();
		} catch (Exception e) {
				System.err.println("### UWS ERROR: "+e.getMessage()+" ###");
				e.printStackTrace();
		}
	}

}
