/**
 * DefaultCallback.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.handler.DefaultHandler;
import com.tandbergtv.watchpoint.pmm.job.util.JobScheduleInfoConstants;

/**
 * This class is the default callback class. Should be ideally used when no titles are associated
 * with the job.
 * 
 * @author spuranik
 */
public class DefaultCallback implements IJobCallback, Job {

	private static final Logger logger = Logger.getLogger(DefaultCallback.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
	 */
	@SuppressWarnings("unchecked")
	public void execute(JobExecutionContext context) throws JobExecutionException {
		DefaultHandler handler = new DefaultHandler();
		Map<String, Object> callbackInfo = (Map<String, Object>) context.getJobDetail()
				.getJobDataMap();

		try {
			handler.executeJob(callbackInfo, new 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());
		DefaultHandler handler = new DefaultHandler();
		try {
			handler.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);
		}
	}

}
