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

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

/**
 * @author Siarhej Chalipau
 *
 */
public class OrderingListRenderingTest extends AbstractAjax4JsfTestCase {
	private static Set javaScripts = new HashSet();
	private static 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/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");
	}
	
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public OrderingListRenderingTest( String testName )
    {
        super( testName );
    }
    
    private final static int ROWS_COUNT = 3;
    
    private UIForm form = null;
    private UIOrderingList orderingList = null;
    private List items = null;
    private HtmlOutputText output1 = null;
    private HtmlOutputText output2 = null;
    private UIColumn column1 = null;
    private UIColumn column2 = null;
    private HtmlOutputText caption = null;

    public void setUp() throws Exception {
    	super.setUp();
    	
    	application.addComponent("org.richfaces.OrderingList", "org.richfaces.component.html.HtmlOrderingList");
    	
    	form = new HtmlForm();
        form.setId("form");
        facesContext.getViewRoot().getChildren().add(form);
    	
    	orderingList = (UIOrderingList)application.createComponent("org.richfaces.OrderingList");
    	orderingList.setId("orderingList");
    	orderingList.setControlsType("link");
    	orderingList.setVar("item");
    	
    	caption =  new HtmlOutputText();
    	caption.setValue("caption");
    	orderingList.getFacets().put("caption", caption);
    	
    	items = new ArrayList();
    	items.add(new SimpleItem("Michael", 2000));
    	items.add(new SimpleItem("John", 500));
    	items.add(new SimpleItem("George", 4000));
    	
    	orderingList.setValue(items);
    	
    	output1 = new HtmlOutputText();
    	output1.setValueBinding("value", application.createValueBinding("#{item.name}"));
    	column1 = new UIColumn();
    	column1.getChildren().add(output1);
    	orderingList.getChildren().add(column1);
    	
    	output2 = new HtmlOutputText();
    	output2.setValueBinding("value", application.createValueBinding("#{item.salary}"));
    	column2 = new UIColumn();
    	column2.getChildren().add(output2);
    	orderingList.getChildren().add(column2);
    	
    	form.getChildren().add(orderingList);
    }
    
    public void tearDown() throws Exception {
    	items = null;
    	output1 = null;
    	output2 = null;
    	column1 = null;
    	column2 = null;
    	orderingList = null;
    	form = null;
    	
    	super.tearDown();
    }

    /**
     * Test script rendering
     *
     * @throws Exception
     */
    public void testRenderScript() throws Exception {
    	HtmlPage page = renderView();
        assertNotNull(page);
        List scripts = page.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++;
                        break;
                    }
                }

                assertTrue(found);
            }
        }
        assertEquals(foundCount, javaScripts.size());
    }
    
    /**
     * 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 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/orderingList.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);
        System.out.println(view.asXml());
        
        List images = view.getDocumentElement().getHtmlElementsByTagName("img");
        assertNotNull(images);
        
        int generatedCount = 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;
        	}
        	generatedCount++;
        	
        	HtmlElement element = (HtmlElement) img.getParentNode();
        	assertNotNull(element);
        	assertEquals("div", element.getNodeName());
        	String clazz = element.getAttributeValue("class");
        	assertNotNull(clazz);
        	assertTrue("rich-ordering-list-button-content".equals(clazz));
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	assertEquals("a", element.getNodeName());
        	String href = element.getAttributeValue("href");
        	assertNotNull(href);
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	if ("a".equalsIgnoreCase(element.getNodeName())) {
        		element = (HtmlElement) element.getParentNode();
        		assertNotNull(element);
        	}
        	assertEquals("div", element.getNodeName());
        	clazz = element.getAttributeValue("class");
        	assertNotNull(clazz);
        	assertTrue(clazz.startsWith("rich-ordering-list-button"));
        	
        	element = (HtmlElement) element.getParentNode();
        	assertNotNull(element);
        	assertEquals("div", element.getNodeName());
        	clazz = element.getAttributeValue("class");
        	assertNotNull(clazz);
        	assertTrue(clazz.contains("rich-ordering-control"));
        }
        assertEquals(8, generatedCount);
    }
    
    /**
     * Test items rendering
     * 
     * @throws Exception
     */
    public void testRenderItems() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        HtmlElement div = view.getHtmlElementById(orderingList.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-ordering-list-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-ordering-list-cell"));
                
                cellsCount++;
            }
            assertEquals(2, cellsCount);
            
            rowsCount++;
        }
        assertEquals(items.size(), rowsCount);
    }
    
    /**
     * Test common rendering
     * 
     * @throws Exception
     */
    public void testRender() throws Exception {
    	HtmlPage view = renderView();
        assertNotNull(view);
        
        HtmlElement div = view.getHtmlElementById(orderingList.getClientId(facesContext));
        assertNotNull(div);
        assertEquals("div", div.getNodeName());
        
        HtmlElement hidden1 = view.getHtmlElementById(orderingList.getClientId(facesContext) + "focusKeeper");
        assertNotNull(hidden1);
        assertEquals("input", hidden1.getNodeName());
        assertEquals("button", hidden1.getAttributeValue("type"));
        hidden1.getAttributeValue("style").contains("left: -32767px");
        
        List hiddens = view.getDocumentElement().getHtmlElementsByAttribute("input", "name", orderingList.getClientId(facesContext));
        assertNotNull(hiddens);
        assertEquals(ROWS_COUNT, hiddens.size());
        for (Iterator it = hiddens.iterator(); it.hasNext(); ) {
        	HtmlElement hidden2 = (HtmlElement) it.next();
        	assertEquals("input", hidden2.getNodeName());
        	assertEquals("hidden", hidden2.getAttributeValue("type"));
        }
    }
    
    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;
		}
    }
}
