package org.richfaces.testng;

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

public class AjaxHTMLCommandLinkTest extends SeleniumTestBase {

    private final static String IS_ACTION_INVOKED = "_form:_action";

    private final static String IS_LISTENER_INVOKED = "_form:_listener";

    private final static String SUBMITTED_VALUE = "_form:_submittedValue";

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

        String parentId = getParentId() + "_form:";
        String linkId = null;

        linkId = parentId + "l2";
        writeStatus("Click link 2");
        clickCommandAndWait(linkId);
        assertValueSubmitted(false);
        assertActionInvoked(false);
        assertListenerInvoked(false);

        linkId = parentId + "l3";
        writeStatus("Click link 3");
        clickCommandAndWait(linkId);
        assertValueSubmitted(false);
        assertActionInvoked(true);
        assertListenerInvoked(true);

        linkId = parentId + "l4";
        writeStatus("Click link 4");
        clickCommandAndWait(linkId);
        assertValueSubmitted(false);
        assertActionInvoked(true);
        assertListenerInvoked(true);

//        linkId = parentId + "l1";
//        writeStatus("Click link 1");
//        clickCommandAndWait(linkId);
//        assertValueSubmitted(true);
//        assertActionInvoked(true);
//        assertListenerInvoked(true);
    }

    private void assertValueSubmitted(boolean submitted) {
        if (submitted) {
            writeStatus("Check that a new value is submitted");
            AssertTextEquals(getParentId() + SUBMITTED_VALUE, "text", "A new value is not submitted");
        } else {
            writeStatus("Check that a new value is not submitted");
            AssertTextEquals(getParentId() + SUBMITTED_VALUE, "", "A new value is submitted");
        }
    }

    private void assertActionInvoked(boolean invoked) {
        if(invoked) {
            writeStatus("Check that action is invoked");
            AssertTextEquals(getParentId() + IS_ACTION_INVOKED, "true", "An action is not invoked");
        } else {
            writeStatus("Check that action is not invoked");
            AssertTextEquals(getParentId() + IS_ACTION_INVOKED, "false", "An action is invoked");
        }
    }

    private void assertListenerInvoked(boolean invoked) {
        if(invoked) {
            writeStatus("Check that listener is invoked");
            AssertTextEquals(getParentId() + IS_LISTENER_INVOKED, "true", "A listener is not invoked");
        } else {
            writeStatus("Check that listener is not invoked");
            AssertTextEquals(getParentId() + IS_LISTENER_INVOKED, "false", "A listener is invoked");
        }
    }

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

}
