/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.richfaces.renderkit.html;




import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import org.ajax4jsf.context.AjaxContext;
import org.ajax4jsf.javascript.JSFunction;
import org.ajax4jsf.renderkit.HeaderResourcesRendererBase;
import org.richfaces.component.UIDropDownMenu;
import org.richfaces.component.UIMenuGroup;
import org.richfaces.component.UIMenuItem;
import org.richfaces.component.UIMenuSeparator;
import org.richfaces.component.util.HtmlUtil;
import org.richfaces.renderkit.ScriptOptions;


public class DropDownMenuRendererBase extends HeaderResourcesRendererBase {

	protected Class getComponentClass() {
		return UIDropDownMenu.class;
	}

	public boolean getRendersChildren() {
		return true;
	}

	public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
		List flatListOfNodes = new LinkedList();
		String width = (String)component.getAttributes().get("popupWidth");

		flatten(component.getChildren(), flatListOfNodes);
		processLayer(context, component, width);

		for (Iterator iter = flatListOfNodes.iterator(); iter.hasNext();) {
			UIMenuGroup node = (UIMenuGroup) iter.next();
			if (node.isRendered() && !node.isDisabled()) processLayer(context, node, width);
		}
	}

	public void processLayer(FacesContext context, UIComponent layer, String width) throws IOException {
		String clientId = layer.getClientId(context);

		ResponseWriter writer = context.getResponseWriter();
		writer.startElement("div", layer);
		writer.writeAttribute("id", clientId+"_menu", null);
		writer.writeAttribute("class", "dr-menu-list-border rich-menu-list-border", null);
		writer.writeAttribute("style", "visibility: hidden; z-index: 2; ", null);
		writer.startElement("div", layer);
		writer.writeAttribute("class", "dr-menu-list-bg rich-menu-list-bg", null);
		encodeItems(context, layer);

		writer.startElement("div", layer);
		writer.writeAttribute("class", "dr-menu-list-strut rich-menu-list-strut", null);

		writer.startElement("img", layer);
		writer.writeAttribute("width", "1", null);
		writer.writeAttribute("height", "1", null);
		writer.writeAttribute("alt", "", null);
		writer.writeAttribute("border", "0", null);
		writer.writeAttribute("style", width!=null && width.length() > 0 ? "width: " + HtmlUtil.qualifySize(width) : "", null);
		writer.writeAttribute("src",
				getResource("/org/richfaces/renderkit/html/images/spacer.gif").getUri(context, null),
				null);
		writer.endElement("img");
		writer.endElement("div");

		writer.endElement("div");
		writer.endElement("div");

		writer.startElement("iframe", layer);
        writer.writeAttribute("src",
            getResource("/org/richfaces/renderkit/html/images/spacer.gif")
                .getUri(context, null), null);
        writer.writeAttribute("id", clientId+"_menu_iframe", null);
		writer.writeAttribute("class", "underneath_iframe", null);
		writer.writeAttribute("style", "position:absolute; z-index: 1;", null);
		writer.endElement("iframe");

		writer.startElement("script", layer);
		writer.writeAttribute("id", clientId+"_menu_script", null);
		writer.writeAttribute("type", "text/javascript", null);
		encodeScript(context, layer);
		writer.endElement("script");

		AjaxContext ajaxContext = AjaxContext.getCurrentInstance();
		Set renderedAreas = ajaxContext.getAjaxRenderedAreas();
		renderedAreas.add(clientId + "_menu_iframe");
		renderedAreas.add(clientId + "_menu_script");
	}

	public void encodeItems(FacesContext context, UIComponent component) throws IOException {
		List kids = component.getChildren();
		Iterator it = kids.iterator();
		while (it.hasNext()) {
			UIComponent kid = (UIComponent)it.next();
			if (kid instanceof UIMenuGroup || kid instanceof UIMenuItem || kid instanceof UIMenuSeparator) {
				renderChild(context, kid);
			}
		}
	}

	private void flatten(List kids, List flatList){
		if(kids != null){
			for (Iterator iter = kids.iterator(); iter.hasNext();) {
				UIComponent kid = (UIComponent) iter.next();
				if (kid instanceof UIMenuGroup) {
					UIMenuGroup node = (UIMenuGroup) kid;
					flatList.add(node);
					flatten(node.getChildren(), flatList);
				}
			}
		}
	}

	public void encodeScript(FacesContext context, UIComponent component) throws IOException {
		StringBuffer buffer = new StringBuffer();
		JSFunction function = new JSFunction("new RichFaces.Menu.Layer");
		function.addParameter(component.getClientId(context)+"_menu");
		function.addParameter(component.getAttributes().get("showDelay"));
        if (component instanceof UIDropDownMenu) {
    		function.addParameter(component.getAttributes().get("hideDelay"));
        }
        else{
        	function.addParameter(""+300);
        }
        function.appendScript(buffer);
		if (component instanceof UIMenuGroup) {
			  buffer.append(".");
			  function = new JSFunction("asSubMenu");
			  function.addParameter(component.getParent().getClientId(context)+"_menu");
			  function.addParameter("ref"+component.getClientId(context));
	 		  String evt = (String) component.getAttributes().get("event");
			  if(evt == null || evt.trim().length() == 0){
				     evt = "onmouseover";
			  }
			  function.addParameter(evt);
			  ScriptOptions Optionssub = new ScriptOptions(component);
			  Optionssub.addOption("onopen", component.getAttributes().get("onopen"));
			  Optionssub.addOption("onclose", component.getAttributes().get("onclose"));
			  Optionssub.addOption("direction", component.getAttributes().get("direction"));
			  function.addParameter(Optionssub);
			  function.appendScript(buffer);

		} else {
			  buffer.append(".");
			  function = new JSFunction("asDropDown");
			  function.addParameter(component.getClientId(context));
  			  String evt = (String) component.getAttributes().get("event");
			  if(evt == null || evt.trim().length() == 0){
					evt = "onmouseover";
			  }
			  function.addParameter(evt);
			  function.addParameter("onmouseout");
			  ScriptOptions Options = new ScriptOptions(component);

			  Options.addOption("direction", component.getAttributes().get("direction"));
			  Options.addOption("jointPoint", component.getAttributes().get("jointPoint"));
			  Options.addOption("verticalOffset", component.getAttributes().get("verticalOffset"));


			  Options.addOption("horizontalOffset", component.getAttributes().get("horizontalOffset"));
			  Options.addOption("oncollapse", component.getAttributes().get("oncollapse"));
			  Options.addOption("onexpand", component.getAttributes().get("onexpand"));
			  Options.addOption("onitemselect", component.getAttributes().get("onitemselect"));
			  Options.addOption("ongroupactivate", component.getAttributes().get("ongroupactivate"));
			  function.addParameter(Options);
			  function.appendScript(buffer);

		}

		List children = component.getChildren();
		for(Iterator it = children.iterator();it.hasNext();) {
			UIComponent kid = (UIComponent)it.next();
			String itemId = null;
			int flcloseonclick=1;
            int flagGroup = 0;
			if (kid instanceof UIMenuItem) {
				UIMenuItem MenuItem=(UIMenuItem)kid;
				itemId = kid.getClientId(context);
				if (MenuItem.isDisabled()){
					flcloseonclick=0;
				}
			} else if (kid instanceof UIMenuGroup) {
                UIMenuGroup menuGroup=(UIMenuGroup)kid;
				itemId = "ref" + kid.getClientId(context);
				flcloseonclick=0;
                if (menuGroup.isDisabled()) flagGroup = 2; else flagGroup = 1;
			}
			if(itemId != null){
				  function = new JSFunction("addItem");
				  function.addParameter(itemId);
				  function.addParameter(new Integer(flcloseonclick));

				  ScriptOptions options = new ScriptOptions(kid);
				  options.addOption("onmouseout", kid.getAttributes().get("onmouseout"));
				  options.addOption("onmouseover", kid.getAttributes().get("onmouseover"));
                  options.addOption("flagGroup", new Integer(flagGroup));
                  String tmp = (String)kid.getAttributes().get("selectClass");
                  if (tmp != null && tmp.length() > 0) options.addOption("selectClass", tmp);
				  function.addParameter(options);
				  buffer.append('.');
				  function.appendScript(buffer);
			}
		}

		ResponseWriter out = context.getResponseWriter();
		String script =buffer.append(";").toString();
		out.write(script);



	}


}
