/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/
// Package
package gov.va.med.fw.scheduling;

// Java classes
import java.util.Properties;

// Libraries
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * SchedulerFactoryBean that does not allow the use of a DataSource (persistent JobStore)
 * in a non-clustered environment.
 * 
 * Created Mar 8, 2006 3:31:32 PM
 * @author DNS   BOHMEG
 * @history: Modified and added comments - VL
 */
public class ClusterAwareSchedulerFactoryBean extends SchedulerFactoryBean  {
	
	public static final String SCHEDULER_AUTO_START = "org.quartz.scheduler.autoStart";
	
	private boolean isClustered = false;

	/**
	 * A default constructor 
	 */
	public ClusterAwareSchedulerFactoryBean() {
		super();
	}
	
	public void afterPropertiesSet() throws Exception {
		
		//
		// There are 2 things we need to override in SchedulerFactoryBean implementation
		//
		// 1. Usage of data source when set
		// 2. Initialize properties that don't apply to RAMJobStore
		//
		// In development environment, to avoid overlapping works between developers, RAMJobStore
		// is encourged in conjunction with single instance of Scheduler while in production 
		// environment, schedulers should be configured in a cluster along with JobStoreCMT - VL
		
		// Check if org.quartz.jobStore.isClustered property is set. unset DataSource in dev env.
		if( !isClustered ) {
			setDataSource( null );
		}
		
		// Only turn off the schedule if a flag is set to false 
		String flag = System.getProperty( SCHEDULER_AUTO_START );
		boolean startScheduler = flag != null && Boolean.FALSE.equals( Boolean.valueOf( flag ) ) ? false : true;
		super.setAutoStartup( startScheduler );
		
		super.afterPropertiesSet();
	}
	
	public void setQuartzProperties( Properties props ) {

		//
		// If "org.quartz.jobStore.isClustered" property is set, it means that 
		// ESR is deployed into a clustered environment which uses JobStoreCMT
		// 
		// If "org.quartz.jobStore.isClustered" property is not set, it means 
		// that ESR is deployed in a single local server and RAMJobStore is used.
		// Remove properties that don't apply to RAMJobStore. - VL
		//
		Object obj = props.get("org.quartz.jobStore.isClustered");
		String value = obj instanceof String ? (String)obj : null;
		this.isClustered = props != null ? Boolean.valueOf( value ).booleanValue() : false; 
		if( !isClustered && props != null) {			
			// remove these settings or else Quartz complains 
			// when not using a persistent JobStore
			props.remove("org.quartz.jobStore.driverDelegateClass");
			props.remove("org.quartz.jobStore.isClustered");
			props.remove("org.quartz.jobStore.clusterCheckinInterval");
		}
		super.setQuartzProperties(props);
	}
}