/**
 * 
 */
package com.tandbergtv.watchpoint.pmm.action.asset.processing;

import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

/**
 * Action handler to select a profile for the XPort Encoder based on certain
 * criteria read from a configuration file.
 * 
 * @author Imran Naqvi
 * 
 */
public class ProfileSelectorAction implements ActionHandler {

	private static final Logger logger = Logger
			.getLogger(ProfileSelectorAction.class);

	private static final String ENCODING_PROFILE = "EncodingProfile";

	/**
	 * 
	 */
	private static final long serialVersionUID = 6646783291083554257L;

	/**
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext executionContext) throws Exception {
		Object obj = executionContext.getVariable(ENCODING_PROFILE);
		/* Do nothing if the EncodingProfile variable is already set to a value */
		if (obj != null && obj.toString().length() > 0)
			return;

		String profileName = findProfile(executionContext);
		logger.debug("Profile Selected:" + profileName);
		executionContext.setVariable(ENCODING_PROFILE, profileName);
	}

	/*
	 * Finds the profile name to set according to the configured criteria.
	 */
	private String findProfile(ExecutionContext executionContext) {
		List<EncoderProfileCriteria> profiles = EncoderProfileCriteriaLoader
				.getInstance().getProfiles();
		for (EncoderProfileCriteria profile : profiles) {
			boolean profileMatch = true;
			HashMap<String, String> criteria = profile.getCriteria();
			for (Object key : criteria.keySet()) {
				String name = key.toString();
				String value = criteria.get(key);

				Object processVar = executionContext.getVariable(name);
				if (processVar == null || !processVar.toString().equals(value)) {
					profileMatch = false;
					break;
				}
			}
			if (profileMatch)
				return profile.getName();
		}

		return EncoderProfileCriteriaLoader.getInstance()
				.getDefaultProfileName();
	}
}
