/*
 * Q70MessageResourcesMenuDisplayer.java
 *
 * Created on February 6, 2001, 3:34 PM
 */
package es.ejie.frmk.presentacion.iu.taglib.html.menu.displayer;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

import org.apache.struts.util.RequestUtils;

import es.ejie.frmk.presentacion.iu.taglib.html.menu.Q70ExpressionEvaluator;
import es.ejie.frmk.presentacion.iu.taglib.html.menu.base.Q70MenuComponent;



/**
 *
 * @author  ssayles
 * @version
 */
public abstract class Q70MessageResourcesMenuDisplayer
    extends Q70AbstractMenuDisplayer {

	//~ Methods ================================================================
	
	/**
	 * Metodos para obtener un recurso de tipo configuracion utilizando el Gestor de Mensajes e Internacionalizacion.
	 * @param key: clave del recurso a obtener
	 * @param arg0, arg1, arg2, arg3: de cero a cuatro posibles argumentos a reemplazar sobre el recurso a obtener
	 * @return: texto del recurso 
	 * @throws JspException
	 */
	public String getConfigMessage(String key) 
		throws JspException 
	{
		return getMessage(super.getListaI18nKey(), key);
	}
	public String getConfigMessage(String key, Object arg0) 
		throws JspException 
	{
		return getMessage(super.getListaI18nKey(), key, arg0);
	}
	public String getConfigMessage(String key, Object arg0, Object arg1) 
		throws JspException 
	{
		return getMessage(super.getListaI18nKey(), key, arg0, arg1);
	}
	public String getConfigMessage(String key, Object arg0, Object arg1, Object arg2) 
		throws JspException 
	{
		return getMessage(super.getListaI18nKey(), key, arg0, arg1, arg2);
	}
	public String getConfigMessage(String key, Object arg0, Object arg1, Object arg2, Object arg3) 
		throws JspException 
	{
		return getMessage(super.getListaI18nKey(), key, arg0, arg1, arg2, arg3);
	}

   
	/**
	 * Metodos para obtener un recurso utilizando el Gestor de Mensajes e Internacionalizacion.
	 * @param i18nKey: clave del ambito donde se encuentra el recurso a obtener 
	 * @param key: clave del recurso a obtener
	 * @param arg0, arg1, arg2, arg3: de cero a cuatro posibles argumentos a reemplazar sobre el recurso a obtener
	 * @return: texto del recurso 
	 * @throws JspException
	 */   
	public String getMessage(List i18nKey, String key) 
		throws JspException 
	{
		Object args[] = null;
		return getI18nKeyMessage(i18nKey, key, args);
	}    	
	public String getMessage(List i18nKey, String key, Object arg0) 
		throws JspException 
	{
		Object args[] = new Object[1];
		args[0] = arg0;		
		return getI18nKeyMessage(i18nKey, key, args);
	}
	public String getMessage(List i18nKey, String key, Object arg0, Object arg1) 
		throws JspException 
	{
		Object args[] = new Object[2];
		args[0] = arg0;
		args[1] = arg1;
		return getI18nKeyMessage(i18nKey, key, args);
	}
	public String getMessage(List i18nKey, String key, Object arg0, Object arg1, Object arg2) 
		throws JspException 
	{
		Object args[] = new Object[3];
		args[0] = arg0;
		args[1] = arg1;
		args[2] = arg2;
		return getI18nKeyMessage(i18nKey, key, args);
	}	
	public String getMessage(List i18nKey, String key, Object arg0, Object arg1, Object arg2, Object arg3) 
		throws JspException 
	{
		Object args[] = new Object[4];
		args[0] = arg0;
		args[1] = arg1;
		args[2] = arg2;	
		args[3] = arg3;		
		return getI18nKeyMessage(i18nKey, key, args);
	}	

	    	
	/**
	 * Get the menu's target (if it exists).  This method
	 * is public to expose it to Velocity.
	 * 
	 * @param menu
	 */
	public String getMenuTarget(Q70MenuComponent menu) {
        String menuTarget = target;

        if (this.target != null) {
            menuTarget = target;
        } else {
            if (menu.getTarget() != null) {
                menuTarget = menu.getTarget();
            } else {
                menuTarget = Q70MenuDisplayer._SELF;
            }
        }

        return menuTarget;
    }

	/**
	 * Get the menu's tooltip (if it exists).  This method
	 * is public to expose it to Velocity.
	 * 
	 * @param menu
	 */
	public String getMenuToolTip(Q70MenuComponent menu) throws JspException 
	{
        String tooltip = EMPTY;

        if (menu.getToolTip() != null) {
            tooltip = getMessage(menu.getListaI18nKey(), menu.getToolTip());
                      
        } else {
            tooltip = getMessage(menu.getListaI18nKey(), menu.getTitle());
        }

        return tooltip;
    }

	/**
	 * Metodo declarado por requisitos del interfaz 
	 */
    public abstract void display(Q70MenuComponent menu,PageContext pageContext)
    throws JspException, IOException;
    

        
	//------------------------------------------------------------------------------------- Private methods
    
	/**
	 * Metodo que obtiene el valor de un recuros de internacionalizacion usando
	 * el Gestor de Mensajes e Internacionalizacion
	 * @param i18nKey: clave del ambito donde buscar el recurso
	 * @param key: clave del recurso 
	 * @param args: parametros a sustituir sobre el texto del recurso
	 * @return
	 * @throws JspException
	 */    
	private String getI18nKeyMessage(List listI18nKey, String key, Object[] args) 
		throws JspException 
	{
		//Obtener el objeto Locale para la clave de session especificada.
		Locale userLocale = RequestUtils.retrieveUserLocale(super.pageContext, super.getLocale()); 

		return super.getI18nMessage(listI18nKey, 
									key,
									userLocale.getLanguage(),
									args);								   	
	}
	
	/**
     * Sets the value for the menu location to the
     * appropriate value if location is null.  If location
     * is null, and the page attribute exists, it's value
     * will be set to the the value for page prepended with
     * the context path of the application.
     *
     * If the page is null, and the forward attribute exists,
     * it's value will be looked up in struts-config.xml.
     *
     *                                     FIXME - ssayles - 121102
     * Ideally, this should happen at menu initialization but
     * I was unable to find a reliable way to get the context path
     * outside of a request.  The performance impact is probably
     * negligable, but it would be better to check for this only once.
     *
     * @param menu The menu component to set the location for.
     */
    protected void setPageLocation(Q70MenuComponent menu)
    	throws MalformedURLException, JspException 
    {
        HttpServletRequest request = (HttpServletRequest)   pageContext.getRequest();
        
        // if the location attribute is null,
        // then set it with a context relative page
        // attribute if it exists
        if (menu.getLocation() == null) 
        {
            if (menu.getPage() != null) 
            {
                // are we sure we'll get an HttpServletRequest?
                menu.setLocation(request.getContextPath() + getPage(menu.getPage()));
            } 
            else if (menu.getForward() != null) 
            {
                String fwd = RequestUtils.computeURL(pageContext, menu.getForward(),
                            					    null, null, null, null, null, false);
                menu.setLocation(fwd);
            } 
            else if (menu.getAction() != null) 
            {
                // generate Struts Action URL,
                // this will append Context Path (if any),
                // Servlet Mapping (path mapping or extension mapping)
                // Module Prefix (if any) & Session ID (if any)
                String action = RequestUtils.computeURL(pageContext, null, null, null,
                               						   menu.getAction(), null, null, false);
                menu.setLocation(action);
            }
        }

        String url = menu.getLocation();

        // Use JSTL to replace dymamic values in the URL
        Q70ExpressionEvaluator eval = new Q70ExpressionEvaluator(this, pageContext);

        String s;
        if ( (s = eval.evalString("url", url)) != null) {
            menu.setUrl(s);
        }

        // do all contained menus
  /*      Q70MenuComponent[] subMenus = menu.getMenuComponents();    

        if (subMenus.length > 0) 
        {
            for (int i = 0; i < subMenus.length; i++) 
            {
            	subMenus[i].setListaI18nKey(getListaI18nKey());
                setPageLocation(subMenus[i]);
            }
        }
       */
    }
    
    /**
     * Returns the value with page prepended with a "/"
     * if it is not already.
     *
     * @param page The value for the page.
     */
    private String getPage(String page) 
    {
        if (page.startsWith("/")) {
            return page;
        } else {
            page = "/" + page;
        }

        return page;
    }
    
    protected void displayComponents(Q70MenuComponent menu, PageContext pageContext){
    	this.pageContext = pageContext;
    	menu.setListaI18nKey(getListaI18nKey());
    	setSecureId(menu.getSecureId());
    }

    
    
}
