/*******************************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ******************************************************************************/
package gov.va.med.esr.ui.taglib;

// Java Classes
import javax.servlet.jsp.JspException;

// Library Classes
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.web.context.WebApplicationContext;

// Framework Classes
import gov.va.med.fw.ui.DelegatingActionUtils;
import gov.va.med.fw.util.StringUtils;
import gov.va.med.fw.model.lookup.Lookup;

// ESR Classes
import gov.va.med.esr.ui.common.service.LookupCacheService;
import gov.va.med.esr.ui.common.util.JspUtils;

/**
 * Tag handler for the displayLookupValue tag.
 * 
 * @author Muddaiah Ranga
 * @version 3.0
 */
public class DisplayLookupValue extends DisplayValue {
	
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 4835375809719382596L;

	// Name of lookup class.
	private String lookupType = null;

	// Optional property on lookup object
	private String lookupProperty = null;

	public String getLookupType() {
		return lookupType;
	}

	public void setLookupType(String lookupType) {
		this.lookupType = lookupType;
	}

	public String getLookupProperty() {
		return lookupProperty;
	}

	public void setLookupProperty(String lookupProperty) {
		this.lookupProperty = lookupProperty;
	}

	/**
	 * Process the start tag.
	 * 
	 * @exception JspException
	 *               if a JSP exception has occurred
	 */
	public int doStartTag() throws JspException {
		if (nullText == null) {
			nullText = JspUtils.NULL_DEFAULT_TEXT;
		}

		String description = null;
		try {
			String lookupId = null;
			Object idObject = super.lookup(pageContext, name, property, scope);
			if (idObject != null) {
				lookupId = idObject.toString();
			}
			if (StringUtils.isNotEmpty(lookupType)	&& StringUtils.isNotEmpty(lookupId)) {
				
				WebApplicationContext ac = DelegatingActionUtils.findRequiredWebApplicationContext( pageContext.getServletContext() );

				LookupCacheService lookupCacheService = 
					(LookupCacheService)ac.getBean( LookupCacheService.LOOKUP_CACHE_SERVICE );
				
				Lookup object = lookupCacheService.getByCodeFromCache(lookupType,lookupId);
				if (object != null) {
					if (StringUtils.isNotEmpty(lookupProperty)) {
						Object lookupObjectProperty = PropertyUtils.getProperty(object, lookupProperty);
						if (lookupObjectProperty != null) {
							description = lookupObjectProperty.toString();
						}
					}
					else {
						description = object.getDescription();
					}
				}
			}
		}
		catch (Exception ex) {
			throw new JspException("Error while getting lookup data.", ex);
		}
		String formatedDescription = JspUtils.displayValue(description, nullText,format);
		// Print the string value to the output writer
		super.write(pageContext, formatedDescription, filter);
		return (SKIP_BODY);
	}
}