/**
 * TitleCallback.java
 * Created on Jun 10, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.job.callback;

import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.tandbergtv.watchpoint.pmm.entities.IContainer;
import com.tandbergtv.watchpoint.pmm.job.execution.WorkOrderCreator;
import com.tandbergtv.watchpoint.pmm.job.handler.TitleAssociatedHandler;
import com.tandbergtv.watchpoint.pmm.job.util.JobScheduleInfoConstants;

/**
 * This class will recv the callback from quartz when its time to execute the job.
 * 
 * @author spuranik
 */
public class TitleCallback extends AbstractJobCallback implements Job {

	private Logger logger = Logger.getLogger(TitleCallback.class);

	/**
	 * Default ctor
	 */
	public TitleCallback() {
		super();
		next = new TitleAssociatedHandler(
			new RuleSetInvoker(new MultipleTitleEvaluator(new WorkOrderCreator(new NoOpCallback()))));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		Map<String, Object> callbackInfo = (Map<String, Object>) context.getJobDetail()
				.getJobDataMap();
		Date date = new Date();
		
		logger.info("Received callback to execute job: "
				+ callbackInfo.get(JobScheduleInfoConstants.JOB_NAME));
		
		try {
			super.preexecute(callbackInfo, date);
			this.next.executeJob(callbackInfo, date);
		} catch (RuntimeException e) {
			IContainer container = CallbackHelper.getContainer(callbackInfo);
			String errorMsg = "Job execution failed for: "
						+ callbackInfo.get(JobScheduleInfoConstants.JOB_NAME) + " ["
						+ container.getContainerType() + ":" + container.getContainerName() + "]";
			logger.error(errorMsg, e);
			throw new JobExecutionException(errorMsg, e);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.tandbergtv.watchpoint.pmm.job.callback.IJobCallback#executeJob(java.util.Map,
	 *      java.util.Date)
	 */
	public void executeJob(Map<String, Object> callbackInfo, Date jobExecutionDate) {
		logger.debug("Executing job that was missed at: " + jobExecutionDate.toString());
		
		try {
			super.preexecute(callbackInfo, jobExecutionDate);
			this.next.executeJob(callbackInfo, jobExecutionDate);
		} catch (RuntimeException e) {
			IContainer container = CallbackHelper.getContainer(callbackInfo);
			String errorMsg = "Job execution failed for missed job: "
						+ callbackInfo.get(JobScheduleInfoConstants.JOB_NAME) + " ["
						+ container.getContainerType() + ":" + container.getContainerName() + "]";
			logger.error(errorMsg, e);
			throw new RuntimeException(errorMsg, e);
		}
	}
}
