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

// Java imports
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.apache.strutsel.taglib.html.ELLinkTag;
import org.springframework.web.context.WebApplicationContext;

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

/**
 * Encrypts the URL's query string.
 * 
 * @author Muddaiah Ranga
 * @version 3.0
 */
public class EncryptedLinkTag extends ELLinkTag {
	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = 5409949795285244534L;

	/**
	 * Return the complete URL to which this hyperlink will direct the user.
	 * Support for indexed property since Struts 1.1
	 * 
	 * @exception JspException
	 *               if an exception is thrown calculating the value
	 */
	protected String calculateURL() throws JspException {
		String url = super.calculateURL();
		// Encrypt the query string part of the url
		if (StringUtils.isNotEmpty(url)) {
			try {
				ServletRequest request = pageContext.getRequest();
				if (request instanceof KeyCache) {
					WebApplicationContext ac = 
						DelegatingActionUtils.findRequiredWebApplicationContext( pageContext.getServletContext() );

					UIEncryptionService encryptionService = 
						(UIEncryptionService) ac.getBean("encryptionService");
					if (encryptionService != null) {
						url = encryptionService.encryptQueryString(request, url);
					}
				}
			}
			catch (Exception ex) {
				new JspException("error while encrypting the link's query string",ex);
			}
		}
		return url;
	}
}
