/**
 * GetMetaDataInfoAction.java
 * Created on Jun 18, 2008
 * (C) Copyright TANDBERG Television Ltd.
 */
package com.tandbergtv.watchpoint.pmm.action.schedule.ingest;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import com.tandbergtv.watchpoint.pmm.util.schedule.ingest.ConversionPropertyReader;

/**
 * This class goes thru the properties file which has the list of providerIds whose incoming
 * schedules and PL contain complete metadata. Based on whether a given providerId is found or not
 * in that list, it sets the 'extractMetadata' variable in the context.
 * 
 * @author spuranik
 * 
 */
public class GetMetaDataInfoAction implements ActionHandler {

	private static final long serialVersionUID = 1L;
	private static String PARTNER_DELIMITER = ",";
	private static String SOURCE_PROVIDER_ID = "providerId";
	private static String EXTRACT_METADATA = "extractMetadata";

	private static final Logger logger = Logger.getLogger(GetMetaDataInfoAction.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jbpm.graph.def.ActionHandler#execute(org.jbpm.graph.exe.ExecutionContext)
	 */
	public void execute(ExecutionContext context) throws Exception {
		String providerId = (String) context.getVariable(SOURCE_PROVIDER_ID);

		String providerList = ConversionPropertyReader
				.getProperty(ConversionPropertyReader.PARTNERS_WITH_METADATA);
		if (providerList == null || providerList.trim().length() == 0) {
			logger
					.debug("Provider list not provided in conversion.properties, so assuming that there metadata need not be extracted for provider: "
							+ providerId);
			context.setVariable(EXTRACT_METADATA, false);
		}

		String[] providers = providerList.split(PARTNER_DELIMITER);
		if (contains(providers, providerId)) {
			logger.debug("Setting 'extractMetadata' to true");
			context.setVariable(EXTRACT_METADATA, true);
		} else {
			logger.debug("Setting 'extractMetadata' to false");
			context.setVariable(EXTRACT_METADATA, false);
		}
	}

	/**
	 * checks if the providerId is present in the providerList supplied
	 * 
	 * @param providers
	 * @param providerId
	 * @return true/false based on whether the providerId is found in the array or not.
	 */
	private boolean contains(String[] providers, String providerId) {

		for (int i = 0; i < providers.length; i++) {
			if (providers[i].equalsIgnoreCase(providerId))
				return true;
		}
		return false;
	}

}
