package core.event;

/*
 * Copyright (c) 2002-2007 TeamDev Ltd. All rights reserved.
 *
 * Use is subject to license terms.
 *
 * The complete licence text can be found at
 * http://www.teamdev.com/winpack/license.jsf
 */

import com.jniwrapper.win32.ie.WebBrowser;
import com.jniwrapper.win32.ie.dom.HTMLElement;
import com.jniwrapper.win32.ie.event.ScriptErrorEvent;
import com.jniwrapper.win32.ie.event.ScriptErrorListener;
import core.BasicSample;

/**
 * This sample demonstrates the technique of listening error events.
 *
 * @author Alexei Orischenko
 */
public class ErrorLoggingSample extends BasicSample
{
    private static final String HTML_CONTENT = "<html>\r\n<body>\r\n" +
            "<button id='errorDiv' onclick='document.all.unexistElement.innerHTML = \"some text\"'>Show error dialog</button>" +
            "</body></html>";

    public ErrorLoggingSample()
    {
        super("Error Logging");
    }

    protected void execute()
    {
        WebBrowser browser = getBrowser();

        // wait when the browser will be ready to work
        browser.waitReady();

        // disable alerts and error dialogs
        browser.setSilent(true);

        browser.setContent(HTML_CONTENT);
        browser.waitReady();

        // setup error listener for current page
        setupScriptErrorListener(browser);

        HTMLElement errorDiv = (HTMLElement)browser.getDocument().getElementById("errorDiv");

        showMessage("Clicked  button that produces script error");
        errorDiv.click();
    }

    private void setupScriptErrorListener(WebBrowser browser)
    {
        browser.setScriptErrorListener(new ScriptErrorListener()
        {
            public void errorOccured(ScriptErrorEvent event)
            {
                int line = event.getLine();
                String url = event.getUrl();
                String message = event.getMessage();

                clearLog();
                info(message);
                info("url: " + url);
                info("line: " + line);

                showLogSwingLoop("Error");
            }
        });
    }

    public static void main(String[] args) throws Exception
    {
        new ErrorLoggingSample().run();
    }
}
