package dom;

/*
 * 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 core.BasicSample;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * This sample demonstrates the technique of navigating through DOM model.
 *
 * @author Alexei Orischenko
 */
public class DomNavigationSample extends BasicSample
{
    private static final String HTML_CONTENT = "<html><body>" +
            "<span>Divs:</span>" +
            "<div id='outer' style='background: #eeeeee; width:600; height: 400; position: absolute; left: 50; top: 50'>" +
            "Outer div" +
            "<div id='inner1' style='background: #cccccc; width:200; height: 100; position: absolute; left: 10; top: 30'>inner 1</div>" +
            "<div id='inner2' style='background: #999999; width:300; height: 50; position: absolute; left: 10; top: 150'>inner 2</div>" +
            "</div>" +
            "<!-- end of outer div -->" +
            "</body></html>";

    public DomNavigationSample()
    {
        super("DOM Navigation");
    }

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

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

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

        printDom(browser.getDocument().getDocumentElement(), 0);

        showLog("Document Object Model");
        clearLog();

        Element outerDiv = browser.getDocument().getElementById("outer");
        int childCount = outerDiv.getChildNodes().getLength();
        NodeList divs = outerDiv.getElementsByTagName("div");
        Element div2 = (Element)divs.item(1);
        Element parent = (Element)div2.getParentNode();
        Comment comment = (Comment)parent.getNextSibling();
    }

    private void printDom(Node node, int offset)
    {
        for (; node != null; node = node.getNextSibling())
        {
            printNode(node, offset);
            printDom(node.getFirstChild(), offset + 1);
        }
    }

    private void printNode(Node node, int offset)
    {
        String offsetStr = getOffset(offset);

        if (node instanceof Element)
        {
            Element element = (Element)node;
            info(offsetStr + node.getNodeName() + ", id = " + element.getAttribute("id"));
        }
        else
        {
            info(offsetStr + node.getNodeName() + ": " + node.getNodeValue());
        }
    }

    private String getOffset(int offset)
    {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < offset; i++)
        {
            result.append("    ");
        }

        return result.toString();
    }

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