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 org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import core.BasicSample;

/**
 * This sample finds input elements in subframe and fill them with values.
 *
 * @author Alexei Orischenko
 */
public class FrameAccessSample extends BasicSample
{
    public FrameAccessSample()
    {
        super("Frame Access");
    }

    protected void execute()
    {
        WebBrowser browser = getBrowser();
        browser.navigate("https://t1.bconline.gov.bc.ca/");
        browser.waitReady();

        Document doc = browser.getDocument();
        NodeList frames = doc.getElementsByTagName("frame");

        showMessage("Set values of the form inputs in frame");

        Element login = getField(frames, "userid");
        if (login != null)
        {
            login.setAttribute("value", "Alex");
        }

        Element password = getField(frames, "password");
        if (password != null)
        {
            password.setAttribute("value", "secret");
        }
    }

    private static Element getField(NodeList frames, String name)
    {
        for (int i = 0; i < frames.getLength(); i++)
        {
            Element frame = (Element)frames.item(i);
            Element password = getField(frame, name);
            if (password != null)
            {
                WebBrowser frameBrowser = (WebBrowser) frame;
                String content = frameBrowser.getContent();
                System.out.println("Content of the frame: " + content);

                return password;
            }
        }

        return null;
    }

    private static Element getField(Element frame, String aName)
    {
        NodeList inputs = frame.getElementsByTagName("input");
        for (int i = 0; i < inputs.getLength(); i++)
        {
            Element input = (Element)inputs.item(i);
            String name = input.getAttribute("name");
            if (aName.equals(name))
            {
                return input;
            }
        }

        return null;
    }

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