/*******************************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ******************************************************************************/
package gov.va.med.fw.rule;

// Java classes
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

// Library classes
import org.apache.commons.lang.Validate;

// Framework classes
import gov.va.med.fw.service.AbstractComponent;

// EDB classes

/**
 * Loads a pre-defined set of rule parameters configured in a spring context
 * file into a rule parameter map and populates all rule parameter of type
 * RuleDataAware with passed-in data from a caller. Project: Framework
 * 
 * @author DNS   LEV
 * @version 1.0
 */
public class ConfigurableRuleParameters extends AbstractRuleParameters {

	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 6450370654925439842L;

	/**
	 * A default constructor
	 */
	public ConfigurableRuleParameters() {
		super();
	}

	/**
	 * Initializes a collection of rule parameters with the data initialized in
	 * this bean.
	 * 
	 * @see gov.va.med.fw.rule.AbstractRuleParameters#initializeRuleParmeters()
	 */
	public void initializeRuleParmeters( RuleDataAware data ) throws RuleConfigurationException {

		// Initialize a list of parameters with a rule data aware
		Map params = getRuleParameters();
		if (params != null && !params.isEmpty()) {
			// Get the rule parameters from the map retrieved above. Cannot do
			// another call to getRuleParameters since it returns new instances.
			Collection values = params.values();
			for (Iterator i = values.iterator(); i.hasNext();) {
				Object value = i.next();
				if (value instanceof RuleParameter) {
					((RuleParameter) value).setRuleDataAware( data );
				}
			}
		}
	}

	/**
	 * @see gov.va.med.fw.rule.RuleParameters#initializeRuleParmeters(java.util.Map)
	 */
	public void initializeRuleParmeters(Map ruleData) throws RuleConfigurationException {
		
		Validate.notEmpty( ruleData, "A rule data map must not be null or empty");
		
		Map params = getRuleParameters();
		if (params != null && !params.isEmpty()) {
			// Get the rule parameters from the map retrieved above. Cannot do
			// another call to getRuleParameters since it returns new instances.
			Collection values = params.values();
			for (Iterator i = values.iterator(); i.hasNext();) {
				Object value = i.next();
				if (value instanceof RuleParameter ) {
					RuleParameter param = (RuleParameter) value;
					Object data = ruleData.get( ((AbstractComponent)param).getBeanName() );
					if( data != null ) {
						param.setRuleDataAware( (RuleDataAware)data );
					}
				}
			}
		}
		
	}
	
	/**
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		Validate.notNull(this.getRuleFlowName(),"A rule flow name must not be null");
	}
}