/**
 * 
 */
package org.richfaces.testng;

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

/**
 * @author Andrey Markavstov
 * 
 */
public class AjaxSupportTest extends SeleniumTestBase {

    @Test
    public void testAjaxSupportComponent(Template template) {
        renderPage(template);
        String parentId = getParentId() + "_form:";

        String dataId = parentId + "data";
        String linkId = parentId + "link";
        String checkBoxId = parentId + "checkbox";
        String command = parentId + "command";

        clickById(linkId);
        waitForAjaxCompletion();
        String data = getTextById(dataId);
        checkMessage(data, A4JSupport.Messages.FOR_LINK, "'onclick' ajax support for link[id='_form:link'] failed.",
                A4JSupport.Messages.FOR_LINK + " successful");

        clickById(checkBoxId);
        waitForAjaxCompletion();
        data = getTextById(dataId);
        checkMessage(data, A4JSupport.Messages.FOR_CHECKBOX,
                "'onchange' ajax support for checkbox[id='_form:checkbox'] failed.", A4JSupport.Messages.FOR_CHECKBOX
                        + " successful");

        clickById(command);
        pause(1000, command);
        if (!data.equals(getTextById(dataId))) {
            writeStatus("<a4j:support failed. 'requestDelay' attribute does not work.");
            Assert.fail("<a4j:support failed. 'requestDelay' attribute does not work.");
        }
        waitForAjaxCompletion();
        data = getTextById(dataId);
        checkMessage(data, A4JSupport.Messages.FOR_COMMAND,
                "'onclick' ajax support for command link[id='_form:command'] failed.", A4JSupport.Messages.FOR_COMMAND
                        + " successful");

        if (A4JSupport.Messages.FOR_SUBMIT.equals(data)) {
            writeStatus("<a4j:support failed. 'disableDefault' attribute does not work");
            Assert.fail("<a4j:support failed. 'disableDefault' attribute does not work.");
        }

    }

    private void checkMessage(String data, String message, String errorMessage, String okMessage) {
        if (message.equals(data)) {
            writeStatus(okMessage);
        } else if (A4JSupport.Messages.NO_DATA.equals(data)) {
            writeStatus(errorMessage + " Caused by: action listener for <a4j:support> skipped", true);
            Assert.fail(errorMessage + " Caused by: action listener for <a4j:support> skipped");
        } else if ("".equals(data)) {
            writeStatus(errorMessage + "Caused by: no ajax request has been sent.", true);
            Assert.fail(errorMessage + "Caused by: no ajax request has been sent.");
        }
    }

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

}
