/**
 * CallbackHelper.java
 * Created on Jul 2, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.job.callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.tandbergtv.watchpoint.pmm.entities.IContainer;
import com.tandbergtv.watchpoint.pmm.entities.JobParameter;
import com.tandbergtv.watchpoint.pmm.job.util.JobScheduleInfoConstants;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.core.service.cache.ICacheService;

/**
 * Contains common methods required by all handlers.
 * 
 * @author spuranik
 */
public class CallbackHelper {

	private static String CONTAINER_CACHE_SERVICE_NAME = "Container Cache";
	
	private static final Logger logger = Logger.getLogger(CallbackHelper.class);

	/**
	 * This method gets the contextId from the callback info, gets the corresponding container
	 * object for this contextId from the container cache and returns this Container.
	 * 
	 * 
	 * @param callbackInfo
	 *            the map which contains the contextId
	 * @return IContainer object for this contextId. It could be null if the contextId does not
	 *         exist in the cache.
	 */
	@SuppressWarnings("unchecked")
	public static IContainer getContainer(Map<String, Object> callbackInfo) {
		Long contextId = ((Long) callbackInfo.get(JobScheduleInfoConstants.CONTEXTID));
		ICacheService<IContainer> containerCache = (ICacheService<IContainer>) ServiceRegistry
				.getDefault().lookup(CONTAINER_CACHE_SERVICE_NAME);
		return (IContainer) containerCache.get(Long.valueOf(contextId));
	}
	
	/**
	 * Shallow copies all entries in the given map but for the job parameters
	 * 
	 * @param callbackInfo
	 *            the map for which a clone is requested
	 * @return a cloned map for the given map
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> clone(Map<String, Object> callbackInfo) {

		Map<String, Object> clonedMap = new HashMap<String, Object>(callbackInfo);
		// everything but for the job params can be a shallow copy
		// this is because the evaluation will substitute values in the job params
		List<JobParameter> jobParamList = new ArrayList<JobParameter>();
		List<JobParameter> callbackJobParams = (List<JobParameter>) callbackInfo.get(JobScheduleInfoConstants.JOB_PARAMETERS);
		
		for (JobParameter parameter : callbackJobParams) {
			JobParameter p = new JobParameter();
			p.setId(parameter.getId());
			p.setJob(parameter.getJob());
			p.setName(parameter.getName());
			p.setValue(parameter.getValue());
			
			logger.debug("Job parameter " + p.getName() + " value " + p.getValue());

			jobParamList.add(p);
		}
		// wipe out the prev job params from the cloned object
		clonedMap.put(JobScheduleInfoConstants.JOB_PARAMETERS, jobParamList);

		return clonedMap;
	}

}
