/**
 * License Agreement.
 *
 * Rich Faces - Natural Ajax for Java Server Faces (JSF)
 *
 * 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;

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

import javax.faces.component.UIColumn;
import javax.faces.component.UIForm;
import javax.faces.component.html.HtmlForm;
import javax.faces.component.html.HtmlOutputText;
import javax.servlet.http.HttpServletResponse;

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.apache.commons.lang.StringUtils;
import org.richfaces.component.UIListShuttle;

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

public class ListShuttleRenderingTest extends AbstractAjax4JsfTestCase {
	private static final int IMAGE_COUNT = 16;
	
	private UIListShuttle listShuttle = null;
	private UIForm form = null;
	private List items = null;
    private HtmlOutputText output1 = null;
    private HtmlOutputText output2 = null;
    private UIColumn column1 = null;
    private UIColumn column2 = null;
	
	private static final Set javaScripts = new HashSet();
	private static final Set imageClasses = new HashSet();
	
	static {
		javaScripts.add("org.ajax4jsf.javascript.PrototypeScript");
		javaScripts.add("scripts/ShuttleUtils.js");
		javaScripts.add("scripts/SelectItem.js");
		javaScripts.add("scripts/LayoutManager.js");
		javaScripts.add("scripts/Control.js");
		javaScripts.add("scripts/OrderingList.js");
		javaScripts.add("scripts/ListShuttle.js");
		javaScripts.add("scripts/ListBase.js");
		
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconUp");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconDown");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconTop");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconBottom");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconUpDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconDownDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconTopDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.OrderingListIconBottomDisabled");
		imageClasses.add("org.richfaces.renderkit.html.gradientimages.OrderingListClickedGradient");
		imageClasses.add("org.richfaces.renderkit.html.gradientimages.OrderingListHeaderGradient");
		imageClasses.add("org.richfaces.renderkit.html.gradientimages.OrderingListButtonGradient");
		
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconCopy");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconCopyDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconCopyAll");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconCopyAllDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconRemove");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconRemoveAll");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconRemoveDisabled");
		imageClasses.add("org.richfaces.renderkit.html.images.ListShuttleIconRemoveAllDisabled");
	}

	/**
     * Create the test case
     *
     * @param testName name of the test case
     */
	public ListShuttleRenderingTest(String testName) {
		super(testName);
	}
	
	public void setUp() throws Exception {
    	super.setUp();
    	
    	application.addComponent(UIListShuttle.COMPONENT_TYPE, "org.richfaces.component.html.HtmlListShuttle");
    	
    	form = new HtmlForm();
        form.setId("form");
        facesContext.getViewRoot().getChildren().add(form);
        
        listShuttle = (UIListShuttle)application.createComponent(UIListShuttle.COMPONENT_TYPE);
        listShuttle.setId("listShuttle");
        listShuttle.setVar("item");
        
        items = new ArrayList();
    	items.add(new SimpleItem("Michael", 2000));
    	items.add(new SimpleItem("John", 500));
    	items.add(new SimpleItem("George", 4000));
    	
    	listShuttle.setSourceValue(items);
    	
    	output1 = new HtmlOutputText();
    	output1.setValueBinding("value", application.createValueBinding("#{item.name}"));
    	column1 = new UIColumn();
    	column1.getChildren().add(output1);
    	listShuttle.getChildren().add(column1);
    	
    	output2 = new HtmlOutputText();
    	output2.setValueBinding("value", application.createValueBinding("#{item.salary}"));
    	column2 = new UIColumn();
    	column2.getChildren().add(output2);
    	listShuttle.getChildren().add(column2);
    	
    	form.getChildren().add(listShuttle);
    }
    
    public void tearDown() throws Exception {
    	super.tearDown();
    	
    	items = null;
    	output1 = null;
    	output2 = null;
    	column1 = null;
    	column2 = null;
    	listShuttle = null;
    	form = null;
    }
    
    /**
     * Test common rendering
     * 
     * @throws Exception
     */
    public void testCommonRendering() throws Exception{
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        HtmlElement table = view.getHtmlElementById(listShuttle.getClientId(facesContext));
        assertNotNull(table);
        assertEquals("table", table.getNodeName());
        
        HtmlElement tbody = (HtmlElement) table.getFirstChild();
        assertNotNull(tbody);
        assertEquals("tbody", tbody.getTagName());
        
        HtmlElement tr = (HtmlElement) tbody.getFirstChild();
        assertNotNull(tr);
        String style = tr.getAttributeValue("style");
        assertNotNull(style);
        assertTrue(style.contains("display: none;"));
        assertEquals("tr", tr.getTagName());
        
        tr = (HtmlElement) tr.getNextSibling();
        assertNotNull(tr);
        assertNull(tr.getNextSibling());
        
        int childCount = 0;
        for (Iterator it = tr.getChildIterator(); it.hasNext();) {
        	HtmlElement td = (HtmlElement) it.next();
        	assertNotNull(td);
        	assertEquals("td", td.getTagName());
        	childCount++;
        }
        assertEquals(4, childCount);
        
        HtmlElement hidden1 = view.getHtmlElementById(listShuttle.getClientId(facesContext) + "focusKeeper");
        assertNotNull(hidden1);
        assertEquals("input", hidden1.getNodeName());
        assertEquals("button", hidden1.getAttributeValue("type"));
        hidden1.getAttributeValue("style").contains("left: -32767px");
        
        List inputs = view.getDocumentElement().getHtmlElementsByAttribute("input", "id", listShuttle.getClientId(facesContext) + "focusKeeper");
        assertNotNull(inputs);
        assertEquals(1, inputs.size());
        inputs = view.getDocumentElement().getHtmlElementsByAttribute("input", "id", listShuttle.getClientId(facesContext) + "tlFocusKeeper");
        assertNotNull(inputs);
        assertEquals(1, inputs.size());
        
        inputs = view.getDocumentElement().getHtmlElementsByAttribute("input", "name", listShuttle.getClientId(facesContext));
        assertNotNull(inputs);
        assertEquals(4, inputs.size());
    }

    /**
     * Test script rendering
     *
     * @throws Exception
     */
    public void testRenderScript() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        List scripts = view.getDocumentElement().getHtmlElementsByTagName("script");
        int foundCount = 0;
        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) {
                    	foundCount++;
                    	
                    	 String uri = "http:" + srcAttr;
                         Page page = webClient.getPage(uri);
                         assertNotNull(page);
                         assertTrue(page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK);
                    	
                        break;
                    }
                }

                assertTrue(found);
            }
        }
        assertEquals(javaScripts.size(), foundCount);
    }
    
    /**
     * Test style rendering
     *
     * @throws Exception
     */
    public void testRenderStyle() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        List links = view.getDocumentElement().getHtmlElementsByTagName("link");
        assertNotNull(links);
        assertEquals(1, links.size());
        HtmlElement link = (HtmlElement) links.get(0);
        assertTrue(link.getAttributeValue("href").contains("css/listShuttle.xcss"));
        
        String uri = "http:" + link.getAttributeValue("href");
        Page page = webClient.getPage(uri);
        assertNotNull(page);
        assertTrue(page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK);
    }
    
    /**
     * Test controls rendering
     * 
     * @throws Exception
     */
    public void testRenderControls() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        List images = view.getDocumentElement().getHtmlElementsByTagName("img");
        assertNotNull(images);
        
        int foundImages = 0;
        for (Iterator it = images.iterator(); it.hasNext(); ) {
        	HtmlElement img = (HtmlElement) it.next();
        	assertNotNull(img);
        	
        	String uri = "http:" + img.getAttributeValue("src");
        	Page page = webClient.getPage(uri);
        	assertNotNull(page);
        	assertTrue(page.getWebResponse().getStatusCode() == HttpServletResponse.SC_OK);
        	
        	if (uri.contains("spacer.gif")) {
        		continue;
        	}
        	foundImages++;
        	
        	HtmlElement element = (HtmlElement) img.getParentNode();
        	assertNotNull(element);
        	assertEquals("div", element.getNodeName());
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	assertEquals("a", element.getNodeName());
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	if ("a".equalsIgnoreCase(element.getNodeName())) {
        		element = (HtmlElement) element.getParentNode();
        		assertNotNull(element);
        	}
        	assertEquals("div", element.getNodeName());
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	assertEquals("div", element.getNodeName());
        	String clazz = element.getAttributeValue("class");
        	assertNotNull(clazz);
        	assertTrue(clazz.contains("rich-shuttle-control"));
        }
        assertEquals(IMAGE_COUNT, foundImages);
    }
    
    /**
     * Test default images rendering
     *
     * @throws Exception
     */
    public void testRenderImages() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        InternetResourceBuilder builder = ResourceBuilderImpl.getInstance();
        
        for (Iterator it = imageClasses.iterator(); it.hasNext(); ) {
        	String clazz = (String) it.next();
        	builder.createResource(null, clazz);
            InternetResource resource = builder.getResource(clazz);
            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());
            assertTrue(info.getHeight() > 0);
            assertTrue(info.getWidth() > 0);
        }
    }
    
    /**
     * Test items rendering
     * 
     * @throws Exception
     */
    public void testRenderItems() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        HtmlElement div = view.getHtmlElementById(listShuttle.getClientId(facesContext) + "contentBox");
        assertNotNull(div);
        assertEquals("div", div.getNodeName());
        
        HtmlElement table = (HtmlElement)div.getFirstChild();
        assertNotNull(table);
        assertEquals("table", table.getNodeName());
        
        HtmlElement tbody = (HtmlElement)table.getFirstChild();
        assertNotNull(tbody);
        assertEquals("tbody", tbody.getNodeName());
        
        int rowsCount = 0;
        for (Iterator it = tbody.getChildIterator(); it.hasNext(); ) {
        	HtmlElement tr = (HtmlElement)it.next();
        	assertNotNull(tr);
            assertEquals("tr", tr.getNodeName());
            
            String clazz = tr.getAttributeValue("class");
            assertNotNull(clazz);
            assertTrue(clazz.contains("rich-shuttle-source-row"));
            
            int cellsCount = 0;
            for (Iterator it2 = tr.getChildIterator(); it2.hasNext(); ) {
            	HtmlElement td = (HtmlElement)it2.next();
            	assertNotNull(td);
                assertEquals("td", td.getNodeName());
                
                String clazz2 = td.getAttributeValue("class");
                assertNotNull(clazz2);
                assertTrue(clazz2.contains("rich-shuttle-source-cell"));
                
                cellsCount++;
            }
            assertEquals(2, cellsCount);
            
            rowsCount++;
        }
        assertEquals(items.size(), rowsCount);
    }

    protected class SimpleItem {
    	String name;
    	int salary;
    	
    	public SimpleItem(String name, int salary) {
    		this.name = name;
    		this.salary = salary;
    	}
    	
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getSalary() {
			return salary;
		}
		public void setSalary(int salary) {
			this.salary = salary;
		}
    }

}
