/********************************************************************
 * Copyright © 2006 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.esr.common.batchprocess.datasync;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

import gov.va.med.esr.common.model.lookup.Relationship;
import gov.va.med.esr.service.LookupService;
import gov.va.med.fw.io.FieldTransformer;
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.service.ServiceException;

/**
 * FieldTransformer for an Association relationship.  ESR stores this as free
 * text and HEC needs the requisite SDS code.
 * 
 * Created May 12, 2006 3:55:00 PM
 * @author DNS   BOHMEG
 */
public class HECLegacyAssociationRelationshipFieldTransformer extends
		AbstractComponent implements FieldTransformer {
	private LookupService lookupService;
	private Map relationshipNameToCodeCache;
	
	/* (non-Javadoc)
	 * @see gov.va.med.fw.io.FieldTransformer#transformData(java.lang.String, java.lang.Object)
	 */
	public Object transformData(String fieldName, Object data) throws Exception {
		String incomingRelationshipText = (String) data;
		if(StringUtils.isBlank(incomingRelationshipText))
			return StringUtils.EMPTY;
		
		Object code = getRelationshipNameToCodeCache().get(incomingRelationshipText.toUpperCase());
		if(code == null)
			code = Relationship.CODE_OTHER.getCode();
		return code;
	}
	
	private synchronized Map getRelationshipNameToCodeCache() throws ServiceException {
		if(relationshipNameToCodeCache == null) {
			relationshipNameToCodeCache = new HashMap();
			// cache Relationships by Name->Code
			List list = lookupService.findAll(Relationship.class);
			Iterator itr = list.iterator();
			Relationship rel = null;
			while(itr.hasNext()) {
				rel = (Relationship) itr.next();
				relationshipNameToCodeCache.put(getRelationshipName(rel).toUpperCase(), rel.getCode());
			}			
		}
		return relationshipNameToCodeCache;
	}

	/**
	 * @return Returns the lookupService.
	 */
	public LookupService getLookupService() {
		return lookupService;
	}

	/**
	 * @param lookupService The lookupService to set.
	 */
	public void setLookupService(LookupService lookupService) {
		this.lookupService = lookupService;
	}

	public void afterPropertiesSet() throws Exception {
		Validate.notNull(lookupService, "A lookupService is required");
	}
	
	private String getRelationshipName(Relationship rel) {
		return StringUtils.isNotBlank(rel.getName()) ? rel.getName() : rel.getDescription();
	}
}
