package es.ejie.frmk.presentacion.iu.taglib.html.menu.displayer;

import java.io.IOException;
import java.net.MalformedURLException;

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

import org.apache.struts.util.RequestUtils;

import es.ejie.frmk.control.excepciones.Q70FrameworkException;
import es.ejie.frmk.infraestructura.traza.Q70TraceLevel;
import es.ejie.frmk.infraestructura.traza.Q70Traza;
import es.ejie.frmk.presentacion.iu.taglib.base.Q70Constants;
import es.ejie.frmk.presentacion.iu.taglib.html.menu.base.Q70MenuComponent;


/**
 * Clase que displaya en web todo un arbol de menu (submenus) en modo Tabbed
 * @version 1.0
 */
public class Q70TabbedMenuDisplayer extends Q70ListMenuDisplayer 
{
	//Instancia del log de trazas
	private static Q70Traza tr = Q70Traza.getSingleton();
	
	/**
	 * @param menu
	 * @param pageContext
	 */
    public void display(Q70MenuComponent menu,PageContext pageContext) throws JspException, IOException 
    {
		super.setSecureId(menu.getSecureId());
		if (Q70Constants.MODE_NOTDISPLAYED != super.getDisplayMode())
		{        	
            displayComponents(menu, 0,pageContext);
        }
    }

    /**
     * Metodo recursivo que pinta el arbol de menus
     * @param menu
     * @param level
     * @param pageContext
     */
    protected void displayComponents(Q70MenuComponent menu, int level,PageContext pageContext)
    	throws JspException, IOException 
    {
    	menu.setListaI18nKey(getListaI18nKey());
        super.displayComponents(menu,pageContext);
        
        try{
    		setPageLocation(menu);
    	}catch (MalformedURLException m)
    	 {	                    
			if (tr.isTraceActive())	{
				tr.trace(COMPONENTE, Q70TraceLevel.ERROR, "Action o forward incorrecto: " + m.getMessage());
				tr.trace(COMPONENTE, Q70TraceLevel.DEBUG, "Estableciendo location a #");
			} 																			                    
            menu.setLocation("#");
        }	
        Q70MenuComponent[] components;
		try {
			components = menu.getMenuComponents();
		} catch (Q70FrameworkException e) {
			if (tr.isTraceActive())
			{
				tr.trace(COMPONENTE, Q70TraceLevel.ERROR, "Error en la obtención de los menus. Q70TabbedMenuDisplayer");
			}
			RequestUtils.saveException(pageContext, e);
			throw new JspException("Error en la obtención de los menus. Q70TabbedMenuDisplayer",e);
		}

        if (components.length > 0) {
            out.print("\t<li>");

            String menuClass = "submenu";

            if (level >= 1) {
                menuClass = "deepmenu";
            }

            if (menu.getUrl() == null) 
            {
				if (tr.isTraceActive())
				{
					tr.trace(COMPONENTE, Q70TraceLevel.INFO, 
								"El menu '" + getMessage(menu.getListaI18nKey(),menu.getTitle()) + 
								"' no tiene definido el atributo location. Se usara el del primer submenu.");					
				}                	
                menu.setUrl(components[0].getUrl());
            }

			printComponent("tmd.menu.tab", menu, menu.getUrl());

            for (int i = 0; i < components.length; i++) {
                // check the permissions on this component
				components[i].setI18nKey(menu.getI18nKey());
				super.setSecureId(components[i].getSecureId());
				if (Q70Constants.MODE_NOTDISPLAYED != super.getDisplayMode())
				{ 				
					try {
						if (components[i].getMenuComponents().length > 0) 
						{
						    // and an <li> for submenus (but not deepmenus)
						    if (menuClass.equals("submenu")) {
						        out.print("<li>");
						    }

						    displayComponents(components[i], level + 1,pageContext);

						    out.println("</ul></li>");

						    if (i == (components[i].getMenuComponents().length - 1)) 
						    { // last one
						        out.println("</li>");
						    }
						} 
						else 
						{
							setPageLocation(components[i]);
							printComponent("tmd.menu.item", components[i], components[i].getLocation());
						}
					}  catch (Q70FrameworkException e) {
						if (tr.isTraceActive())
						{
							tr.trace(COMPONENTE, Q70TraceLevel.ERROR, "Error en la obtención de los menus. Q70TabbedMenuDisplayer");
						}
						RequestUtils.saveException(pageContext, e);
						throw new JspException("Error en la obtención de los menus. Q70TabbedMenuDisplayer",e);
					}
                }
            }
            // close the </ul> for the top menu
            if (menuClass.equals("submenu")) {
                out.println("\t</ul>");
            }
            out.print("\t</li>");
        } 
        else 
        {
			printComponent("tmd.menu.item", menu, menu.getUrl());
        }
    }

    /**
     * This will output the ending javascript statements to intialize each menu
     * <code>END_STATEMENT</code> and <code>SCRIPT_END</code>
     * @param context
     */
    public void end(PageContext context) 
    {
        try 
        {
            out.print(getConfigMessage("lmd.end"));
        } 
        catch (Exception e) {
			if (tr.isTraceActive())
			{
				tr.trace(COMPONENTE, Q70TraceLevel.ERROR, "Q70TabbedMenuDisplayer: throwable en metodo end(): " + e.getMessage());
			}    
        }
    }

	/**
	 * Manda al navegador el codigo para pintar el componente (solo si seguridad lo permite).
	 * @param key: clave del recurso de internacionalizacion
	 * @param menu: objeto menu 
	 * @param level: nivel de profuncidad del menu
	 * @throws JspException
	 */
	private void printComponent(String key, Q70MenuComponent menu, String url)
		throws JspException, IOException 
	{
		super.setSecureId(menu.getSecureId());
		menu.setPageContext(pageContext);
    	menu.setListaI18nKey(getListaI18nKey());
    			
		if (Q70Constants.MODE_NOTDISPLAYED != super.getDisplayMode())
		{ 		        	
			out.println(getConfigMessage(key,
										 url, 
										 super.getMenuToolTip(menu),
										 getMessage(menu.getListaI18nKey(),menu.getTitle())));
		}
	}
}
