package gov.va.med.fw.ui.taglib;

// Java imports
import gov.va.med.fw.security.KeyCache;
import gov.va.med.fw.ui.DelegatingActionUtils;
import gov.va.med.fw.ui.security.UIEncryptionService;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.taglib.TagUtils;
import org.apache.strutsel.taglib.html.ELHiddenTag;
import org.springframework.web.context.WebApplicationContext;

/**
 * Encrpts the value of the hidden field.
 * 
 * @author Muddaiah Ranga
 * @version 3.0
 */
public class EncryptedHiddenTag extends ELHiddenTag {
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -4662985691047562339L;

	/**
	 * Generate the required input tag, followed by the optional rendered text.
	 * Support for <code>write</code> property since Struts 1.1.
	 * 
	 * @exception JspException
	 *               if a JSP exception has occurred
	 */
	public int doStartTag() throws JspException {
		// If the value is not provided, get it using the lookup.
		if (StringUtils.isEmpty(value)) {
			Object valueObject = TagUtils.getInstance().lookup(pageContext, name,
					property, null);
			if (valueObject != null)
				value = valueObject.toString();
		}

		// Encrypt the hidden field's value
		if (StringUtils.isNotEmpty(value)) {
			try {
				ServletRequest request = pageContext.getRequest();
				if (request instanceof KeyCache) {
					WebApplicationContext ac = 
						DelegatingActionUtils.findRequiredWebApplicationContext( pageContext.getServletContext() );
					UIEncryptionService encryptionService = 
						(UIEncryptionService)ac.getBean("encryptionService");
					if (encryptionService != null) {
						value = encryptionService.encryptHiddenField(request, value);
					}
				}
			}
			catch (Exception ex) {
				new JspException(
						"error while encrypting the hidden field's value.", ex);
			}
		}

		// Render the <html:input type="hidden"> tag as before
		return super.doStartTag();
	}
}
