/********************************************************************
 * Copyright © 2006 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.scheduling;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.quartz.LocalDataSourceJobStore;

/**
 * Custom SchedulerFactory that provides custom JobStore behavior
 * via PersistentJobStore.  Primarily needed because Spring does not
 * provide a way to inject usage of a custom JobStore.
 * 
 * <p>Not a Spring managed bean since it is instantiated via reflection
 * in SchedulerFactoryBean
 * 
 * <p>CAN BE REMOVED AFTER QUARTZ 1.6.x INTEGRATION, although could
 * exist beyond that for JobStore injection (given Spring 2.x supports that).
 * 
 * Created Nov 2, 2006 3:44:29 PM
 * 
 * @author DNS   BOHMEG
 */
public class CustomSchedulerFactory extends StdSchedulerFactory {
	protected final Log logger = LogFactory.getLog(getClass());
	private Class jobStoreClass = PersistentJobStore.class;
	private static Class SPRING_PERSISTENT_JOB_STORE = LocalDataSourceJobStore.class;
	
	/**
	 * invoked from Spring SchedulerFactoryBean.initSchedulerFactory
	 */
	public void initialize(Properties props) throws SchedulerException {
		if(jobStoreClass != null) {
			boolean replaced = false;
			String oldValue = (String) props.get(PROP_JOB_STORE_CLASS);			
			// if Spring was using a persistent JobStore, replace with custom one...					
			if(SPRING_PERSISTENT_JOB_STORE.getName().equals(oldValue)) {
				// ....but only if it  extends from SPRING_PERSISTENT_JOB_STORE (preserves Spring value added)
				if(SPRING_PERSISTENT_JOB_STORE.isAssignableFrom(jobStoreClass)) {
					replaced = true;
					props.put(PROP_JOB_STORE_CLASS, jobStoreClass.getName());
				}
			} else {
				// this means Spring is not using a persistent job store, so use this custom one if not persistent
				if(!SPRING_PERSISTENT_JOB_STORE.isAssignableFrom(jobStoreClass)) {
					replaced = true;
					props.put(PROP_JOB_STORE_CLASS, jobStoreClass.getName());
				}
			}
			if(replaced && logger.isWarnEnabled()) {
				logger.warn("CustomSchedulerFactory overruled usage of JobStore [" + oldValue + "] in favor of more robust [" + 
						jobStoreClass.getName() + "]");
			}			
		}
		super.initialize(props);
	}

	/**
	 * @return Returns the jobStoreClass.
	 */
	public Class getJobStoreClass() {
		return jobStoreClass;
	}

	/**
	 * @param jobStoreClass The jobStoreClass to set.
	 */
	public void setJobStoreClass(Class jobStoreClass) {
		this.jobStoreClass = jobStoreClass;
	}
}
