package org.richfaces.testng;

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


public class InputNumberSpinnerTest extends SeleniumTestBase {

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

        writeStatus("check whether the spinner is invariant with respect to pair of sequential opposite operations");
        
        //start value = 20
        String before = getSpinnerValue();
        clickUp();
        clickDown();
        String after = getSpinnerValue();
        Assert.assertEquals(before, after);
        Assert.assertEquals(after, "20");

        writeStatus("check upper bound and cycling");

        clickUp(); //+10
        clickUp(); //+10
        clickUp(); //+10
        clickUp(); //+10
        clickUp(); //+10
        Assert.assertEquals(getSpinnerValue(), "10");

        writeStatus("check lower bound and cycling");

        clickDown(); //-10
        Assert.assertEquals(getSpinnerValue(), "0");
        clickDown(); //-10
        Assert.assertEquals(getSpinnerValue(), "50");
        clickDown(); //-10
        Assert.assertEquals(getSpinnerValue(), "40");
    }

    private void clickUp() {
        String id = getParentId() + "_form:" + "spinnerButtons";
        selenium.fireEvent("xpath=//table[@id='" + id + "']/tbody/tr[1]/td/input", "mousedown");
        selenium.fireEvent("xpath=//table[@id='" + id + "']/tbody/tr[1]/td/input", "mouseup");
    }

    private void clickDown() {
        String id = getParentId() + "_form:" + "spinnerButtons";
        selenium.fireEvent("xpath=//table[@id='" + id + "']/tbody/tr[2]/td/input", "mousedown");
        selenium.fireEvent("xpath=//table[@id='" + id + "']/tbody/tr[2]/td/input", "mouseup");
    }

    private String getSpinnerValue() {
        return selenium.getValue("name=" + getParentId() + "_form:spinner");
    }

    public String getTestUrl() {
        return "pages/inputNumberSpinner/inputNumberSpinnerTest.xhtml";
    }

}
