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.SimpleTrigger;

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 JobTriggerEditAction 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);
	
		JobTriggerForm info = (JobTriggerForm)form;
		
		MessageResources messages = getResources(request);
	
		// Was this transaction cancelled?
		if (isCancelled(request)) {
			if (log.isInfoEnabled()) {
				log.info(" " + mapping.getAttribute() + " - HtmlexpDefineEditAction transaction was cancelled");
			}
			removeFormBean(mapping, request);
			return (mapping.findForward("success"));
		}
				
		if (log.isDebugEnabled()) {
			log.debug("JobEditAction:  Processing actions");
		}
		String startTime = info.getStartTime();
		String stopTime = info.getStopTime();
		
		boolean startTimeHasValue =
			((startTime != null) && (startTime.length() > 0));
		boolean stopTimeHasValue =
			((stopTime != null) && (stopTime.length() > 0));
		boolean repeatCountHasValue = (info.getRepeatCount() != null);
		boolean repeatIntervalHasValue = (info.getRepeatInterval() != null);

		SimpleTrigger simpleTrigger = null;

		int repeatCount = 0;
		long repeatInterval = 0;
		try {
			repeatCount = Integer.parseInt(info.getRepeatCount());
		} catch (Exception e) {}
		try {
			repeatInterval = Integer.parseInt(info.getRepeatInterval());
		} catch (Exception e) {}

		if (startTimeHasValue && (!stopTimeHasValue)) {
			simpleTrigger =
				new SimpleTrigger(
					info.getTriggerName(),
					info.getTriggerGroup(),
					info.getStartTimeAsDate());
		} else if (!startTimeHasValue) {
			simpleTrigger =
				new SimpleTrigger(
					info.getTriggerName(),
					info.getTriggerGroup(),
					repeatCount,
					repeatInterval);
		} else {
			simpleTrigger =
				new SimpleTrigger(
					info.getTriggerName(),
					info.getTriggerGroup(),
					info.getStartTimeAsDate(),
					info.getStopTimeAsDate(),
					repeatCount,
					repeatInterval);
		}

		simpleTrigger.setJobName(info.getJobName());
		simpleTrigger.setJobGroup(info.getJobGroup());
		simpleTrigger.setVolatility(false);
		
		try {
			Scheduler scheduler = JobSchedulerUtils.getCurrentScheduler(session);
			scheduler.scheduleJob(simpleTrigger);
		} catch (SchedulerException e) {

			if (log.isDebugEnabled()) {
				log.debug("JobTriggerEditAction:  Processing actions");
			}
			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());
           }
       }
    }
}

