package org.richfaces.testng;

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

public class AjaxPushTest extends SeleniumTestBase {

    @Test(dataProvider = "templates")
    public void testAjaxPushComponent(Template template) throws Exception {
        renderPage(template);
        
        String parentId = getParentId() + "_form:";

        String startBtnID = parentId + "startButton";
        String stopBtnID  = parentId + "stopButton";

        String startPanelID     = parentId + "startPanel";
        String progressPanelID  = parentId + "progressPanel";

        writeStatus("Check layout before start pushing");

        AssertRendered(startBtnID);
        AssertRendered(startPanelID);

        AssertNotRendered(stopBtnID);
        AssertNotRendered(progressPanelID);

        writeStatus("Start push component. Test bean has to start sending events to registered PushEventListener");

        clickAjaxCommandAndWait(startBtnID);

        writeStatus("Check layout after pushing started");

        AssertNotRendered(startBtnID);
        AssertNotRendered(startPanelID);

        AssertRendered(stopBtnID);
        AssertRendered(progressPanelID);

        writeStatus("check whether push events are being fired");

        int eventBefore = getEventsCount();

        delay(3000);

        int eventAfter = getEventsCount();

        if(eventBefore >= eventAfter) {
            Assert.fail("PushEvents are not fired");
        }

        writeStatus("stop pushing");

        clickAjaxCommandAndWait(stopBtnID);

        writeStatus("Check layout after pushing stopped");

        AssertRendered(startBtnID);
        AssertRendered(startPanelID);

        AssertNotRendered(stopBtnID);
        AssertNotRendered(progressPanelID);

    }

    private int getEventsCount() throws Exception {
        String events = getTextById(getParentId() + "_form:events");
        try {
            return Integer.parseInt(events);
        } catch (Exception e) {
            Assert.fail("Quantity of sent events is not numeric  :" + e.getMessage());
            throw new Exception(e);
        }
    }

    @Override
    public String getTestUrl() {
        return "pages/ajaxPush/ajaxPushTest.xhtml";
    }

}
