package com.eactive.eai.rms.onl.common.scheduler;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.quartz.Scheduler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

public class SchedulerBeanFactoryProcessor implements BeanPostProcessor {

	private Scheduler scheduler;
	private static Logger logger = Logger.getLogger(SchedulerBeanFactoryProcessor.class);

	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

		if (AnnotationUtils.isAnnotationDeclaredLocally(Schedule.class, bean.getClass())) {
			Class<?> clazz = bean.getClass();

			Method[] methods = clazz.getMethods();

			for (Method method : methods) {
				ScheduleMethod scheduledMethod = findScheduledMethod(method);

				if (scheduledMethod != null) {
					try {
						scheduleJob(bean, beanName, method, bean.getClass(), scheduledMethod);
					} catch (Exception e) {
						logger.error(" error : ", e);
					}
				}
			}
		}

		return bean;
	}

	private void scheduleJob(Object bean, String beanName, Method method, Class<? extends Object> clazz,
			ScheduleMethod scheduledMethod) throws Exception {
	}

	private ScheduleMethod findScheduledMethod(Method method) {
		return AnnotationUtils.findAnnotation(method, ScheduleMethod.class);
	}

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
		logger.debug("scheduler : " + this.scheduler);
	}

}
