
import java.io.File;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import uws.UWSException;
import uws.UWSToolBox;

import uws.job.JobList;

import uws.service.BasicUWS;
import uws.service.UWSUrl;
import uws.service.UserIdentifier;

import uws.service.controller.DestructionTimeController.DateField;

public class UWSTimers extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected BasicUWS<JobChrono> uws = null;
	protected File restoreFile = null;
	
	@SuppressWarnings("unchecked")
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		ServletContext context = config.getServletContext();
		
		// Fetch the results directory path:
		String resultsDirectoryPath = context.getRealPath("/jobResults");
		JobChrono.setResultDirectory(resultsDirectoryPath);
		
		// Restore the last saved UWS, if any:
		restoreFile = new File(context.getRealPath("/"), "uwsRestore");
		uws = (BasicUWS<JobChrono>) UWSToolBox.restoreUWS(restoreFile, true);
		
		// If no saved UWS has been found, initialize the UWS:
		if (uws == null){
			// Ensure the results directory is empty:
			UWSToolBox.clearDirectory(resultsDirectoryPath);
			
			try{
				// Create the UWS:
				uws = new BasicUWS<JobChrono>(JobChrono.class);
				
				// Set the destruction time for all jobs:
				uws.getDestructionTimeController().setDefaultDestructionInterval(1, DateField.MONTH);
				uws.getDestructionTimeController().setMaxDestructionInterval(1, DateField.MONTH);
				
				// Set the execution time for all jobs:
				uws.getExecutionDurationController().setDefaultExecutionDuration(3600);
				uws.getExecutionDurationController().setMaxExecutionDuration(3600);
				
				// Set the way the UWS must identify a user:
				uws.setUserIdentifier(new UserIdentifier() {
					private static final long serialVersionUID = 1L;

					@Override
					public String extractUserId(UWSUrl urlInterpreter, HttpServletRequest request) throws UWSException {
						return request.getRemoteAddr();
					}
				});
				
				// Set a description:
				uws.setDescription("This UWS aims to manage one (or more) JobList(s) of JobChrono." +
									"JobChrono is a kind of Job whose the execution task consists to wait a given time" +
									"before executing an action.");
				
				// Create the job list "timers":
				uws.addJobList(new JobList<JobChrono>("timers"));
				
				// Add an action to get the last executed action:
				uws.addUWSAction(0, new GetLastAction(uws));
			}catch(UWSException ex){
				throw new ServletException(ex);
			}
		}
	}

	@Override
	public void destroy() {
		// Save the current state of this UWS:
		UWSToolBox.saveUWS(uws, restoreFile, true);
		super.destroy();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try{
			// FORWARD THE REQUEST TO THE UWS:
			uws.executeRequest(req, resp);
			
		}catch(UWSException uwsEx){
			// Display properly the caught UWSException:
			resp.sendError(uwsEx.getHttpErrorCode(), uwsEx.getMessage());
		}
	}
}
