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

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
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.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

/**
 * @author Jrmt
 */
public class SchedulerControler extends ScheduleBase {

    /**
     * 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
	 *
	 * @exception Exception if an input/output error or servlet exception occurs
	 */
	public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {

		// Extract attributes we will need
		HttpSession session = request.getSession();
		Locale locale = getLocale(request);
		
		MessageResources messages = getResources(request);
	    String command = getCommand(request);
        log.info("command is = " + command);

        SchedulerChooseForm scheduleInfo = (SchedulerChooseForm)form;

        if( scheduleInfo == null ){
            scheduleInfo = new SchedulerChooseForm();
        }
        
        String newSchedulerName = scheduleInfo.getChoosenSchedulerName();
        Scheduler choosenScheduler = null;
        try {

            if (newSchedulerName != null && newSchedulerName.length() > 0)
                choosenScheduler = new StdSchedulerFactory().getScheduler(newSchedulerName);
            else {
                choosenScheduler = StdSchedulerFactory.getDefaultScheduler();
            }

            if ("start".equalsIgnoreCase( command )) {
                choosenScheduler.start();

            } else if ("stop".equalsIgnoreCase( command )) {
                choosenScheduler.shutdown();
                choosenScheduler = StdSchedulerFactory.getDefaultScheduler();

            } else if ("pause".equalsIgnoreCase( command )) {
                choosenScheduler.pause();

            } else if ("waitAndStop".equalsIgnoreCase( command ) ) {
                choosenScheduler.shutdown(true);

            } else if ("pauseAll".equalsIgnoreCase( command ) ) {
                choosenScheduler.pauseAll();

            } else if ("resumeAll".equalsIgnoreCase( command ) ) {
                choosenScheduler.resumeAll();
            }

            this.populateSchedulerForm(choosenScheduler, scheduleInfo);

            request.setAttribute( "ChoosenScheduler", choosenScheduler );
            request.setAttribute( "SchedulerChooseForm", scheduleInfo );
            
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mapping.findForward("success");
        
    }

    private void populateSchedulerForm(Scheduler choosenScheduler, SchedulerChooseForm form)
            throws Exception {

        Collection scheduleCollection = new StdSchedulerFactory().getAllSchedulers();
        Iterator itr = scheduleCollection.iterator();

        form.setSchedulers(new ArrayList());
        try {
            form.setChoosenSchedulerName(choosenScheduler.getSchedulerName());

            while (itr.hasNext()) {
                Scheduler scheduler = (Scheduler) itr.next();
                form.getSchedulers().add(scheduler);
            }

        } catch (SchedulerException e) {
            throw new Exception(e);
        }

        SchedulerDTO schedForm = new SchedulerDTO();
        schedForm.setSchedulerName(choosenScheduler.getSchedulerName());
        schedForm.setNumJobsExecuted(String.valueOf(choosenScheduler.getMetaData()
                .numJobsExecuted()));

        if (choosenScheduler.getMetaData().jobStoreSupportsPersistence()) {
            schedForm.setPersistenceType("DataBase");
        } else {
            schedForm.setPersistenceType("RAM"); // mp
                                                                                      // possible
                                                                                      // bugfix
        }
        schedForm.setRunningSince(String.valueOf(choosenScheduler.getMetaData().runningSince()));
        if (choosenScheduler.isShutdown()) {
            schedForm.setState("停止中");
        } else if (choosenScheduler.isPaused()) {
            schedForm.setState("暫停中");
        } else {
            schedForm.setState("起動中");
        }

        schedForm.setThreadPoolSize(String.valueOf(choosenScheduler.getMetaData()
                .getThreadPoolSize()));
        schedForm.setVersion(choosenScheduler.getMetaData().getVersion());
        schedForm.setSummary(choosenScheduler.getMetaData().getSummary());

        List jobDetails = choosenScheduler.getCurrentlyExecutingJobs();
        for (Iterator iter = jobDetails.iterator(); iter.hasNext();) {
            JobExecutionContext job = (JobExecutionContext) iter.next();
            JobDetail jobDetail = job.getJobDetail();

            JobDetailForm jobForm = new JobDetailForm();
            jobForm.setGroupName(jobDetail.getGroup());
            jobForm.setName(jobDetail.getName());
            jobForm.setDescription(jobDetail.getDescription());
            jobForm.setJobClass(jobDetail.getJobClass().getName());

            form.getExecutingJobs().add(jobForm);
        }
        String calendars[] = choosenScheduler.getCalendarNames();

        List jobListeners = choosenScheduler.getGlobalJobListeners();
        for (Iterator iter = jobListeners.iterator(); iter.hasNext();) {
            JobListener jobListener = (JobListener) iter.next();
            JobListenerForm listenerForm = new JobListenerForm();
            listenerForm.setListenerName(jobListener.getName());
            listenerForm.setListenerClass(jobListener.getClass().getName());
            schedForm.getGlobalJobListeners().add(listenerForm);
        }

        // The section commented out below is not currently used, but may be
        // used to show triggers that have been
        // added to jobs

        /*
         * List triggerListeners = choosenScheduler.getGlobalTriggerListeners();
         * for (Iterator iter = triggerListeners.iterator(); iter.hasNext();) {
         * TriggerListener triggerListener = (TriggerListener) iter.next();
         * ListenerForm listenerForm = new ListenerForm();
         * listenerForm.setListenerName(triggerListener.getName());
         * listenerForm.setListenerClass(triggerListener.getClass().getName());
         * schedForm.getGlobalJobListeners().add(listenerForm); }
         * 
         * Set jobListenerNames = choosenScheduler.getJobListenerNames(); for
         * (Iterator iter = jobListenerNames.iterator(); iter.hasNext();) {
         * JobListener jobListener = choosenScheduler.getJobListener((String)
         * iter.next()); ListenerForm listenerForm = new ListenerForm();
         * listenerForm.setListenerName(jobListener.getName());
         * listenerForm.setListenerClass(jobListener.getClass().getName());
         * schedForm.getRegisteredJobListeners().add(listenerForm); }
         * 
         * Set triggerListenerNames =
         * choosenScheduler.getTriggerListenerNames(); for (Iterator iter =
         * triggerListenerNames.iterator(); iter.hasNext();) { TriggerListener
         * triggerListener = choosenScheduler.getTriggerListener((String)
         * iter.next()); ListenerForm listenerForm = new ListenerForm();
         * listenerForm.setListenerName(triggerListener.getName());
         * listenerForm.setListenerClass(triggerListener.getClass().getName());
         * schedForm.getRegisteredTriggerListeners().add(listenerForm); }
         * 
         * List schedulerListeners = choosenScheduler.getSchedulerListeners();
         * for (Iterator iter = schedulerListeners.iterator(); iter.hasNext();) {
         * SchedulerListener schedulerListener = (SchedulerListener)
         * iter.next(); ListenerForm listenerForm = new ListenerForm();
         * listenerForm.setListenerClass(schedulerListener.getClass().getName());
         * schedForm.getSchedulerListeners().add(listenerForm); }
         *  
         */

        //TODO fix this
        form.setScheduler(schedForm);

    }

    private String getCommand( HttpServletRequest request ){
        
        String result = null;
        String button = request.getParameter( "start.x" );
        if( button != null && !"".equals(button) ){
            return "start";
        }
        button = request.getParameter( "start.y" );
        if( button != null && !"".equals(button) ){
            return "start";
        }
        button = request.getParameter( "pause.x" );
        if( button != null && !"".equals(button) ){
            return "pause";
        }
        button = request.getParameter( "pause.y" );
        if( button != null && !"".equals(button) ){
            return "pause";
        }
        button = request.getParameter( "stop.x" );
        if( button != null && !"".equals(button) ){
            return "stop";
        }
        button = request.getParameter( "stop.y" );
        if( button != null && !"".equals(button) ){
            return "stop";
        }
        button = request.getParameter( "waitAndStopScheduler.x" );
        if( button != null && !"".equals(button) ){
            return "waitAndStopScheduler";
        }
        button = request.getParameter( "waitAndStopScheduler.y" );
        if( button != null && !"".equals(button) ){
            return "waitAndStopScheduler";
        }
        button = request.getParameter( "btnPauseAllJobs.x" );
        if( button != null && !"".equals(button) ){
            return "btnPauseAllJobs";
        }
        button = request.getParameter( "btnPauseAllJobs.y" );
        if( button != null && !"".equals(button) ){
            return "btnPauseAllJobs";
        }
        button = request.getParameter( "btnResumeAllJobs.x" );
        if( button != null && !"".equals(button) ){
            return "btnResumeAllJobs";
        }
        button = request.getParameter( "btnResumeAllJobs.y" );
        if( button != null && !"".equals(button) ){
            return "btnResumeAllJobs";
        }
        
        
        return result;
    }
}

/*
 * need to populate the following
 * 
 * schedulerName scheduleState runningSince numJobsExecuted persistenceType
 * threadPoolSize version
 * 
 * 
 * lists Schedulers-name
 * 
 * chooseScheduler - executing jobs groupName name description jobClass
 * 
 * 
 * chooseScheduler.summary
 *  
 */

