/*******************************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ******************************************************************************/
package gov.va.med.esr.common.rule.service.impl;

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

import org.apache.commons.lang.Validate;

import gov.va.med.fw.model.AbstractEntity;
import gov.va.med.fw.rule.AbstractRuleFlowAwareService;

import gov.va.med.esr.common.rule.service.MatchRuleService;

/**
 * Encapsulates logics to compare 2 entities for matching on the same "domain concept".
 *
 * Project: Common</br>
 * Created on: 4:50:43 PM </br>
 *
 * @author DNS   LEV
 */
public final class MatchRuleServiceImpl extends AbstractRuleFlowAwareService implements MatchRuleService {

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

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

	/**
	 * @see gov.va.med.esr.common.rule.service.MatchRuleService#findMatchingElement(gov.va.med.fw.model.AbstractEntity, java.util.Collection)
	 */
	public final AbstractEntity findMatchingElement(AbstractEntity source, Collection target) {
		Validate.notNull( source, "A source to find a match must not be null" );
		Validate.notNull( target, "A target collection in which a match is searched must not be null");
		
		AbstractEntity match = null;
		for( Iterator i=target.iterator(); i.hasNext(); ) {
			Object element = i.next();
			Validate.isTrue( (element instanceof AbstractEntity), "An invalid type to find a match" );
			if( source.matchesDomainConcept(element ) ) {
				match = (AbstractEntity)element;
				break;
			}
		}
		return match;
	}

	/**
	 * @see gov.va.med.esr.common.rule.service.MatchRuleService#match(gov.va.med.fw.model.AbstractEntity, gov.va.med.fw.model.AbstractEntity)
	 */
	public final boolean match(AbstractEntity source, AbstractEntity target) {
		
		Validate.notNull( source, "A source must not be null" );
		Validate.notNull( target, "A target must not be null" );
		return source.matchesDomainConcept(target);
	}        
}