/**
 * 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.component;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.html.HtmlForm;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.event.PhaseId;
import javax.servlet.http.HttpServletResponse;

import org.ajax4jsf.event.EventsQueue;
import org.ajax4jsf.resource.InternetResource;
import org.ajax4jsf.resource.InternetResourceBuilder;
import org.ajax4jsf.resource.ResourceBuilderImpl;
import org.ajax4jsf.resource.image.ImageInfo;
import org.ajax4jsf.tests.AbstractAjax4JsfTestCase;
import org.ajax4jsf.tests.MockViewRoot;
import org.apache.commons.collections.Buffer;
import org.apache.commons.lang.StringUtils;
import org.richfaces.component.html.HtmlMenuItem;
import org.richfaces.renderkit.html.images.background.MenuItemBackground;

import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlScript;

/**
 * Unit test for MenuItem Component.
 */
public class MenuItemComponentTest extends AbstractAjax4JsfTestCase {
    private static Set javaScripts = new HashSet();

    static {
        javaScripts.add("PrototypeScript");
        javaScripts.add("AjaxScript");
        javaScripts.add("org/richfaces/renderkit/html/scripts/utils.js");
        javaScripts.add("org/ajax4jsf/javascript/scripts/form.js");
        javaScripts.add("org/richfaces/renderkit/html/scripts/form.js");
    }

    private UIMenuItem menuItem;

    private UIForm form;

    /**
     * Create the test case
     * 
     * @param testName
     *            name of the test case
     */
    public MenuItemComponentTest(String testName) {
        super(testName);
    }

    public void setUp() throws Exception {
        super.setUp();

        form = new HtmlForm();
        form.setId("form");
        facesContext.getViewRoot().getChildren().add(form);

        menuItem = (UIMenuItem) application
                .createComponent(HtmlMenuItem.COMPONENT_TYPE);
        menuItem.setId("menuItem");
        menuItem.setValue("Menu Item");

        form.getChildren().add(menuItem);
    }

    public void tearDown() throws Exception {
        super.tearDown();
        menuItem = null;
        form = null;
    }

    /**
     * MenuItem rendering test.
     */
    public void testMenuItemRender() throws Exception {
        menuItem.setSubmitMode(MenuComponent.MODE_NONE);
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement div = page.getHtmlElementById(menuItem
                .getClientId(facesContext));
        assertNotNull(div);
        assertEquals("div", div.getNodeName());
    }

    /**
     * MenuItem facet test.
     */
    public void testMenuItemIconFacet() throws Exception {
        UIComponent text = createComponent(HtmlOutputText.COMPONENT_TYPE,
                HtmlOutputText.class.getName(), null, null, null);
        menuItem.getFacets().put("icon", text);
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement span = page.getHtmlElementById(menuItem
                .getClientId(facesContext)
                + ":icon");
        assertEquals("span", span.getNodeName());
        assertNotNull(span);
    }

    /**
     * MenuItem facet test.
     */
    public void testMenuItemDisabledIconFacet() throws Exception {
        UIComponent text = createComponent(HtmlOutputText.COMPONENT_TYPE,
                HtmlOutputText.class.getName(), null, null, null);
        menuItem.getFacets().put("iconDisabled", text);
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement span = page.getHtmlElementById(menuItem
                .getClientId(facesContext)
                + ":icon");
        assertEquals("span", span.getNodeName());
        assertNotNull(span);
    }

    /**
     * Test for MenuItem disabled component.
     */
    public void testDisabledMenuItem() throws Exception {
        menuItem.setDisabled(true);
        menuItem.getAttributes().put("iconDisabled", "menuItemIconDisabled");
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement span = page.getHtmlElementById(menuItem
                .getClientId(facesContext)
                + ":anchor");
        assertNotNull(span);
        assertEquals("span", span.getNodeName());
        String classAttr = span.getAttributeValue("class");
        assertTrue(classAttr
                .contains("rich-menu-item-label rich-menu-item-label-disabled"));

        span = page.getHtmlElementById(menuItem.getClientId(facesContext)
                + ":icon");
        assertNotNull(span);
        assertEquals("span", span.getNodeName());
        classAttr = span.getAttributeValue("class");
        assertTrue(classAttr
                .contains("dr-menu-icon rich-menu-item-icon dr-menu-icon-disabled rich-menu-item-icon-disabled"));

        HtmlElement div = page.getHtmlElementById(menuItem
                .getClientId(facesContext));
        assertNotNull(div);
        assertEquals("div", div.getNodeName());
        classAttr = div.getAttributeValue("class");
        assertTrue(classAttr
                .contains("dr-menu-item dr-menu-item-disabled rich-menu-item rich-menu-item-disabled"));
        classAttr = div.getAttributeValue("onmouseout");
        assertEquals(0, classAttr.length());
        classAttr = div.getAttributeValue("onmouseover");
        assertEquals(0, classAttr.length());
    }

    /**
     * Test for enabled MenuItem component in "server" mode.
     */
    public void testEnabledMenuItemServerMode() throws Exception {
        assertEquals(false, menuItem.isDisabled());
        menuItem.getAttributes().put("iconClass", "iconClass");
        menuItem.setSubmitMode(MenuComponent.MODE_SERVER);
        menuItem.getAttributes().put("target", "target");
        menuItem.getAttributes().put("selectStyle", "menuItemSelectStyle");
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement anchor = page.getHtmlElementById(menuItem
                .getClientId(facesContext)
                + ":anchor");
        assertNotNull(anchor);
        assertEquals("span", anchor.getNodeName());
        String classAttr = anchor.getAttributeValue("class");
        assertTrue(classAttr.contains("rich-menu-item-label"));

        HtmlElement span = page.getHtmlElementById(menuItem
                .getClientId(facesContext)
                + ":icon");
        assertNotNull(span);
        assertEquals("span", span.getNodeName());
        classAttr = span.getAttributeValue("class");
        assertTrue(classAttr.contains("dr-menu-icon rich-menu-item-icon"));
        assertTrue(classAttr.contains((String) menuItem.getAttributes().get(
                "iconClass")));

        HtmlElement div = page.getHtmlElementById(menuItem
                .getClientId(facesContext));
        assertNotNull(div);
        assertEquals("div", div.getNodeName());
        classAttr = div.getAttributeValue("class");
        assertTrue(classAttr
                .contains("dr-menu-item dr-menu-item-enabled rich-menu-item rich-menu-item-enabled"));
        classAttr = div.getAttributeValue("onclick");
        assertNotNull(classAttr);
        assertTrue(classAttr.length() > 0);
        classAttr = div.getAttributeValue("onmouseover");
        assertTrue(classAttr.contains("menuItemSelectStyle"));
    }

    /**
     * Test for enabled MenuItem component in "ajax" mode.
     */
    public void testEnabledMenuItemAJAXMode() throws Exception {
        menuItem.setSubmitMode(MenuComponent.MODE_AJAX);
        menuItem.getAttributes().put("style", "menuItemStyle");
        HtmlPage page = renderView();
        assertNotNull(page);
        //System.out.println(page.asXml());
        HtmlElement div = page.getHtmlElementById(menuItem
                .getClientId(facesContext));
        assertNotNull(div);
        String classAttr = div.getAttributeValue("onclick");
        assertTrue(classAttr.contains("AJAX"));
        classAttr = div.getAttributeValue("style");
        assertTrue(classAttr.contains("menuItemStyle"));
    }

    /**
     * Test for enabled MenuItem component in "none" mode.
     */
    public void testEnabledMenuItemNoneMode() throws Exception {
        menuItem.setSubmitMode(MenuComponent.MODE_NONE);
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        HtmlElement div = page.getHtmlElementById(menuItem
                .getClientId(facesContext));
        assertNotNull(div);
        String classAttr = div.getAttributeValue("onclick");
        assertNotNull(classAttr);
        assertTrue(classAttr.length() > 0);
    }

    /**
     * CSS link test.
     */
    public void testRenderStyle() throws Exception {
        HtmlPage page = renderView();
        assertNotNull(page);
        List links = page.getDocumentElement().getHtmlElementsByTagName("link");
        // assertEquals(1, links.size());
        assertNotNull(links);
        HtmlElement link = (HtmlElement) links.get(0);
        assertTrue(link.getAttributeValue("href").contains(
                "menucomponents.xcss"));
    }

    /**
     * Scripts link test.
     */
    public void testRenderScript() throws Exception {
        HtmlPage page = renderView();
        assertNotNull(page);
        // System.out.println(page.asXml());
        List scripts = page.getDocumentElement().getHtmlElementsByTagName(
                "script");
        for (Iterator it = scripts.iterator(); it.hasNext();) {
            HtmlScript item = (HtmlScript) it.next();
            String srcAttr = item.getSrcAttribute();

            if (StringUtils.isNotBlank(srcAttr)) {
                boolean found = false;
                for (Iterator srcIt = javaScripts.iterator(); srcIt.hasNext();) {
                    String src = (String) srcIt.next();

                    found = srcAttr.contains(src);
                    if (found) {
                        break;
                    }
                }

                assertTrue(found);
            }
        }
    }

    /**
     * DoDecode method trst. Component in "AJAX" mode. Immediate is true.
     */
    public void testMenuItemDoDecodeAJAXMode() throws Exception {

        menuItem.setImmediate(true);
        menuItem.setSubmitMode(MenuComponent.MODE_AJAX);

        externalContext.getRequestParameterMap().put(
                menuItem.getClientId(facesContext), "Action");
        menuItem.decode(facesContext);

        MockViewRoot mockViewRoot = (MockViewRoot) facesContext.getViewRoot();
        EventsQueue events = mockViewRoot.getEventsQueue(PhaseId.APPLY_REQUEST_VALUES);
        assertNotNull(events);
        assertEquals(1, events.size());
    }

    /**
     * DoDecode method trst. Component in "server" mode. Immediate is false.
     */
    public void testMenuItemDoDecodeServerMode() throws Exception {

        menuItem.setImmediate(false);
        menuItem.setSubmitMode(MenuComponent.MODE_SERVER);

        externalContext.getRequestParameterMap().put(
                menuItem.getClientId(facesContext) + ":hidden", "Action");
        menuItem.decode(facesContext);

        MockViewRoot mockViewRoot = (MockViewRoot) facesContext.getViewRoot();
        EventsQueue events = mockViewRoot.getEventsQueue(PhaseId.INVOKE_APPLICATION);
        assertNotNull(events);
        assertEquals(1, events.size());
    }

    /**
     * Test accessibility of static image resource.
     */
    public void testMenuItemDefaultIconImage() throws Exception {

        renderView();
        InternetResourceBuilder builder = ResourceBuilderImpl.getInstance();
        String iconImage = "org/richfaces/renderkit/html/images/spacer.gif";
        InternetResource resource = builder.getResource(iconImage);
        assertNotNull(resource);
        String uri = "http:" + resource.getUri(facesContext, null);
        Page page = webClient.getPage(uri);
        assertTrue(page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK);
        ImageInfo info = new ImageInfo();
        info.setInput(page.getWebResponse().getContentAsStream());
        assertTrue(info.check());
        assertEquals(ImageInfo.FORMAT_GIF, info.getFormat());
    }

    public void testRenderImages() throws Exception {
        renderView();
        InternetResourceBuilder builder = ResourceBuilderImpl.getInstance();
        InternetResource resource = builder.createResource(null,
                MenuItemBackground.class.getName());
        assertNotNull(resource);
        String uri = "http:" + resource.getUri(facesContext, null);
        Page page = webClient.getPage(uri);
        assertTrue(page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK);
        ImageInfo info = new ImageInfo();
        info.setInput(page.getWebResponse().getContentAsStream());
        // image recognizable?
        assertTrue(info.check());
        assertEquals(ImageInfo.FORMAT_GIF, info.getFormat());
    }

}
