package com.jware.apps.scheduler.web.struts.schedule;

import java.util.Locale;

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


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.UICronTrigger;

import com.jware.apps.scheduler.util.JobSchedulerUtils;
import com.jware.base.error.JwareApplicationException;
import com.jware.base.web.struts.jWareBaseAction;

/**
 * @author Jrmt
*/
public final class JobUITriggerEditAction extends jWareBaseAction {

    /**
     * Commons Logging instance.
    */
    private Log log = LogFactory.getLog(this.getClass().getName());

	/** 
	 * Process the specified HTTP request, and create the corresponding HTTP
	 * response (or forward to another web component that will create it).
	 * Return an <code>ActionForward</code> instance describing where and how
	 * control should be forwarded, or <code>null</code> if the response has
	 * already been completed.
	 *
	 * @param mapping The ActionMapping used to select this instance
	 * @param actionForm The optional ActionForm bean for this request (if any)
	 * @param request The HTTP request we are processing
	 * @param response The HTTP response we are creating
	 * @param errors The ActionErrors created in BaseAction
	 * @param mochFlag The flag using Mocha
	 *
	 * @exception Exception if an input/output error or servlet exception occurs
	 */
	public ActionForward doExecute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response,
				 ActionErrors errors,
				 boolean mochaFlag)
	throws Exception {

		// Extract attributes we will need
		HttpSession session = request.getSession();
		Locale locale = getLocale(request);
	
		JobUITriggerForm info = (JobUITriggerForm)form;
		
		MessageResources messages = getResources(request);
		
		// Was this transaction cancelled?
		if (isCancelled(request)) {
			if (log.isInfoEnabled()) {
				log.info(" " + mapping.getAttribute() + " - JobUITriggerEditAction transaction was cancelled");
			}
			removeFormBean(mapping, request);
			return (mapping.findForward("success"));
		}
		
		if (log.isDebugEnabled()) {
			log.debug("JobUITriggerEditAction:  Processing actions");
		}
		String startTime = info.getStartTime();
		String stopTime = info.getStopTime();
		
		boolean startTimeHasValue =
			((startTime != null) && (startTime.length() > 0));
		boolean stopTimeHasValue =
			((stopTime != null) && (stopTime.length() > 0));

		UICronTrigger trigger = new UICronTrigger();
		trigger.setJobGroup( info.getJobGroup() );
		trigger.setJobName( info.getJobName() );
		trigger.setGroup( info.getTriggerGroup() );
		trigger.setName( info.getTriggerName() );

		if( info.getYears() != null) {
			trigger.setYears( info.getYears() );
		}
		if( info.getMonths() != null) {
			trigger.setMonths( info.getMonths() );
		}
		if( info.getDaysOfMonth() != null ) {
			trigger.setDaysOfMonth( info.getDaysOfMonth() );
		}
		if( info.getDaysOfWeek() != null ) {
			trigger.setDaysOfWeek( info.getDaysOfWeek() );
		}
		if( info.getHours() != null ) {
			trigger.setHours( info.getHours() );
		}
		if( info.getMinutes() != null ) {
			trigger.setMinutes( info.getMinutes() );
		}
		if( info.getSeconds() != null ) {
			trigger.setSeconds( info.getSeconds() );
		}
		
		// test for parse expression erro error.cronExpression.parseError
		trigger.setDescription(info.getDescription());
		if (startTimeHasValue) {
			trigger.setStartTime(info.getStartTimeAsDate());
		}
		
		if (stopTimeHasValue) {
			trigger.setEndTime(info.getStopTimeAsDate());
		}
		
		// todo look at volativily later
		trigger.setVolatility(false);
		
		try {
			Scheduler scheduler = JobSchedulerUtils.getCurrentScheduler(session);
			scheduler.scheduleJob(trigger);
		} catch (SchedulerException e) {

			if (log.isDebugEnabled()) {
				log.debug("JobCronTriggerEditAction:  Scheduler Error occurs.");
			}
			throw new JwareApplicationException("E600001", e);
		
		}
	
		return mapping.findForward("success");
		
    }

    /**
     * Convenience method for removing the obsolete form bean.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param request The HTTP request we are processing
    */
    protected void removeFormBean(ActionMapping mapping, HttpServletRequest request) {
       // Remove the obsolete form bean
       if (mapping.getAttribute() != null) {
           if ("request".equals(mapping.getScope())) {
               request.removeAttribute(mapping.getAttribute());
           } else {
              HttpSession session = request.getSession();
              session.removeAttribute(mapping.getAttribute());
           }
       }
    }
}

