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

import java.util.Iterator;
import java.util.LinkedList;
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.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

import com.jware.apps.scheduler.model.JobParameterValue;
import com.jware.apps.scheduler.util.JobSchedulerUtils;
import com.jware.base.web.struts.jWareBaseAction;

/**
 * @author Jrmt
*/
public final class JobScheduleView 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);
		
		JobScheduleViewForm info = (JobScheduleViewForm)form;
		
		MessageResources messages = getResources(request);
		
		if (log.isDebugEnabled()) {
			log.debug("JobScheduleView:  Processing actions");
		}

		if( info == null ){
			info = new JobScheduleViewForm();
		}
		JobDetail jobDetail = null;
		String jobName = request.getParameter( "jobName" );
		if( jobName == null ){
			jobName = (String)session.getAttribute( "jobName" );
		}
		session.setAttribute( "jobName", jobName );
		String groupName = request.getParameter( "groupName" );
		if( groupName == null ){
			groupName = (String)session.getAttribute( "groupName" );
		}
		if( jobName != null && groupName != null ){

			Scheduler scheduler = JobSchedulerUtils.getCurrentScheduler(session);
			jobDetail = scheduler.getJobDetail( jobName, groupName );
			
			if( jobDetail != null ){
				
				info.setName(jobName);
				info.setGroupName( groupName );
				info.setDescription(jobDetail.getDescription());
				info.setDescription(jobDetail.getDescription());
				info.setJobClass(jobDetail.getJobClass().getName());
				info.setVolatility(jobDetail.isVolatile());
				info.setDurable(jobDetail.isDurable());
				
				info.getParamMap().put("jobName", jobName);
				info.getParamMap().put("groupName", groupName);

				JobDataMap jobDataMap = jobDetail.getJobDataMap();
				List parameters = new LinkedList();

				String[] parameterNames = jobDataMap.getKeys();
				for(int i=0; i<parameterNames.length;i++){
					String parameterName = parameterNames[i];
					if( jobDataMap.get( parameterName ) != null ){
						JobParameterValue jobParameterValue = new JobParameterValue();
						jobParameterValue.setParameterName( parameterName );
						jobParameterValue.setParameterValue( jobDataMap.get( parameterName ).toString() );
						parameters.add(jobParameterValue);
					}
				}
				info.setJobParameters( parameters );
				populateForm( jobDetail, info, scheduler);
			}
			
			request.setAttribute( "jobViewForm", info );
			session.setAttribute( "jobName", jobName );
			session.setAttribute( "groupName", groupName );
			
			return mapping.findForward("success");
			
		}
		
		return mapping.findForward("failure");
		
    }

    private void populateForm(JobDetail jobDetail, JobScheduleViewForm viewForm,
            Scheduler scheduler) {

    	Trigger[] triggers = JobSchedulerUtils.getTriggersFromJob(scheduler, jobDetail
                .getName(), jobDetail.getGroup());
      
        for (int i = 0; i < triggers.length; i++) {
            Trigger trigger = triggers[i];
            JobTriggerForm tForm = new JobTriggerForm();
            tForm.setDescription(trigger.getDescription());
            tForm.setJobGroup(trigger.getJobGroup());
            tForm.setJobName(trigger.getJobName());
            tForm.setMisFireInstruction(trigger.getMisfireInstruction());
            tForm.setStartTime(JobSchedulerUtils.getDateAsString(trigger.getStartTime()));
            tForm.setStopTime(JobSchedulerUtils.getDateAsString(trigger.getEndTime()));
            tForm.setTriggerGroup(trigger.getGroup());
            tForm.setTriggerName(trigger.getName());
            tForm.setNextFireTime(JobSchedulerUtils.getDateAsString(trigger
                    .getNextFireTime()));
            tForm.setPreviousFireTime(JobSchedulerUtils.getDateAsString(trigger
                    .getPreviousFireTime()));
            tForm.setType(JobSchedulerUtils.getTriggerType(trigger));
            tForm.getParamMap().put("triggerName", trigger.getName());
            tForm.getParamMap().put("groupName", trigger.getGroup());

            tForm.getJobParamMap().put("jobName", trigger.getJobName());
            tForm.getJobParamMap().put("groupName", trigger.getJobGroup());

            viewForm.getJobTriggers().add(tForm);
        }
      
        try {
            String[] jobListenerNames = jobDetail.getJobListenerNames();
            for (Iterator iter = scheduler.getJobListenerNames().iterator(); iter
                    .hasNext();) {
                String name = (String) iter.next();
                JobListener jobListener = scheduler.getJobListener(name);
                for (int i = 0; i < jobListenerNames.length; i++) {
                    if (jobListener.getName().equals(jobListenerNames[i])) {
                        JobListenerForm listenerForm = new JobListenerForm();
                        listenerForm.setListenerName(jobListener.getName());
                        listenerForm.setListenerClass(jobListener.getClass()
                                .getName());
                        viewForm.getJobListeners().add(listenerForm);
                    }
                }
            }
        } catch (SchedulerException e) {
        }
    }
	
}

