package org.richfaces.testng;

import org.ajax4jsf.template.Template;
import org.richfaces.SeleniumTestBase;
import org.testng.Assert;
import org.testng.annotations.Test;

public class PickListTest extends SeleniumTestBase {

    @Test
    public void testPickListComponent(Template template) {
        renderPage(template);

        String parentId = getParentId() + "_form:";
        String pickListId = "pickList";
        String copyElemId = parentId + pickListId + "discopy";
        String copyAllElemId = parentId + pickListId + "copyAll";
        String removeElemId = parentId + pickListId + "disremove";
        String removeAllElemId = parentId + pickListId + "removeAll";

        writeStatus("Check move controls customized labels");

        AssertTextEquals(copyElemId,      "MOVE");
        AssertTextEquals(copyAllElemId,   "MOVE ALL");
        AssertTextEquals(removeElemId,    "TAKE AWAY");
        AssertTextEquals(removeAllElemId, "TAKE ALL AWAY");

        String destListId = parentId + pickListId + "tlTbody";
        String srcListId = parentId + pickListId + "tbody";

        writeStatus("Check initial disposition");

        Assert.assertEquals(getNumberOfChildren(srcListId),  6);
        Assert.assertEquals(getNumberOfChildren(destListId), 2);

        writeStatus("Verify initial selected items.");

        Assert.assertEquals(selenium.getText("xpath=//tbody[@id='" + destListId + "']/tr[1]"), "ZHURIK");
        Assert.assertEquals(selenium.getText("xpath=//tbody[@id='" + destListId + "']/tr[2]"), "MELESHKO");

        writeStatus("Try to select first item and check state thereafter");

        selenium.doubleClick("xpath=//tbody[@id='" + srcListId + "']/tr/td");

        Assert.assertEquals(getNumberOfChildren(srcListId), 5);
        Assert.assertEquals(getNumberOfChildren(destListId), 3);
        Assert.assertEquals(selenium.getText("xpath=//tbody[@id='" + destListId + "']/tr[3]"), "LEONTIEV");

    }

    /**
     * Returns number of children for DOM element with given id.
     * @param elemId DOM element id
     * @return number of children
     */
    private int getNumberOfChildren(String elemId) {
        int retVal = -1;
        try {
            retVal = Integer.parseInt(runScript("dom=selenium.browserbot.getCurrentWindow().$('" + elemId
                    + "').childElements().size()"));
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }

        return retVal;
    }

    public String getTestUrl() {
        return "pages/pickList/pickListTest.xhtml";
    }

}
