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

import java.util.List;
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.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.jware.apps.scheduler.model.JobParameterValue;
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 JobEditAction 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);
	
		JobEditForm info = (JobEditForm)form;
		info.setJobParameters( request );
		
		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");
		}
		
		JobDetail jobDetail = new JobDetail();
		jobDetail.setGroup( info.getGroupName( ));
		jobDetail.setName( info.getName( ));
		jobDetail.setDescription( info.getDescription( ));
		jobDetail.setVolatility( info.isVolatility() );
		jobDetail.setDurability( info.isDurable() );
		jobDetail.setRequestsRecovery( info.isRecoveryRequesting() );

		String className = info.getJobClass();
		
		List parameters = info.getJobParameters();
		jobDetail.setJobDataMap(new JobDataMap());
		
		Class jobClass = null;
		try {
			jobClass = Class.forName(className);
			jobDetail.setJobClass(jobClass);
			
			for (int i =0; i < parameters.size(); i++) {
				JobParameterValue jobParameterValue = (JobParameterValue)parameters.get(i);
				String parameterName = jobParameterValue.getParameterName();
				String parameterValue = jobParameterValue.getParameterValue();
				
				if (parameterName != null && parameterName.trim().length() > 0 &&
						parameterValue != null && parameterValue.trim().length() > 0) {
					jobDetail.getJobDataMap().put(parameterName, parameterValue);
				}
								
			}
			boolean replace = true;
			Scheduler scheduler = JobSchedulerUtils.getCurrentScheduler(session);
			scheduler.addJob(jobDetail, replace);
			
			session.setAttribute( "jobName", info.getName() );
			session.setAttribute( "groupName", info.getGroupName() );
		
		} catch (ClassNotFoundException e) {

			if (log.isDebugEnabled()) {
				log.debug("JobEditAction: "+ className+ " class is not found");
			}
			String[] args = new String[1];
			args[0] = className;
			throw new JwareApplicationException("E500002", args, e);
			
		} catch (SchedulerException e) {
			if (log.isDebugEnabled()) {
				log.debug("JobEditAction: scheduler Error " + e.getMessage());
			}
			throw new JwareApplicationException("E600001", e);
			
		} catch (IllegalArgumentException e) {
			if (log.isDebugEnabled()) {
				log.debug("JobEditAction: scheduler Error " + e.getMessage());
			}
			throw new JwareApplicationException("E600002", 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());
           }
       }
    }
}

