package dom;

import com.jniwrapper.win32.ie.dom.HTMLDocument;
import com.jniwrapper.win32.ie.Browser;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;

import javax.swing.*;

/**
 * @author Ikryanov Vladimir
 */
public class SetBaseElementSample
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        final Browser browser = new Browser();
        frame.setContentPane(browser);
        frame.setSize(800, 600);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        browser.navigate("www.google.com");
        browser.waitReady();

        setContent("www.google.com", browser);
    }

    public static void setContent(String baseHref, Browser browser)
    {
        HTMLDocument document = browser.getDocument();
        String baseTag = "base";
        NodeList elementsByTagName = document.getElementsByTagName(baseTag);
        if (elementsByTagName.getLength() == 0)
        {
            Element element = document.createElement(baseTag);
            element.setAttribute("href", baseHref);
            document.getHead().appendChild(element);
        }
        else
        {
            for (int i = 0; i < elementsByTagName.getLength(); i++)
            {
                Node node = elementsByTagName.item(i);
                NamedNodeMap attributes = node.getAttributes();
                Node namedItem = attributes.getNamedItem("href");
                if (namedItem != null)
                {
                    namedItem.setNodeValue(baseHref);
                }
            }
        }

        browser.setContent(browser.getContent());
        browser.waitReady();
    }
}
