/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.accesstracking;


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.Set;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;

import scone.util.AlertBox;



/**
 * This thread demonstrates the use of the FrameAccess class.
 * It creates a little GUI with following features:
 * <ul>
 *   <li>A list of frameNames to choose one</li>
 *   <li>A text field for an URL</li>
 *   <li>A list to choose one of the targets</li>
 *   <li>A button to send the OpenURL command</li>
 *   <li>A button to send the BringToFront command</li>
 * </ul>
 *
 * @author Torsten Hass, Harald Weinreich
 * @version 1.1, 02/13/2003
 */
public class FrameAccessTest extends Thread {

    private MyFrameAccess mfa;
    private Iterator iterator;
    private String[] frameNameList = {"No open frames"};
    private String[] targetList = {"_self", "_parent", "_top", "_blank"};
    private JList list;
    private DefaultListModel listModel;

    // Components for the GUI
    private JFrame containerFrame;
    final JTextField url = new JTextField("http://www.scone.de/", 20);
    final JComboBox target = new JComboBox(targetList);
    private JButton openUrl;
    private JButton toFront;
    private JButton close;
    private JButton blur;
    private JButton test;
    private JScrollPane listScrollPane;
    private JPanel pane;
   
    /**
     * This method starts the thread and opens the gui.
     */
    public void run() {

        // set look and feel
        try {
            UIManager.setLookAndFeel(
                    UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) {}

        containerFrame = new JFrame("FrameAccess Test GUI");
        ImageIcon img = new ImageIcon("resources/scone/scone64.gif");

        containerFrame.setIconImage(img.getImage());  // Set icon of program
        FrameAccessTest app = new FrameAccessTest();

        listModel = new DefaultListModel();
        listModel.addElement("List is empty");
      
        list = new JList(listModel);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setSelectedIndex(0);
        listScrollPane = new JScrollPane(list);
            
        target.setEditable(true);
      
        openUrl = new JButton("Open Above URL");
        openUrl.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //
                // That way you call the applet's OpenURL function
                //
                // get a reference of FrameAccess
                // fa = FrameAccess.g getInstance();
                // get a reference of AppletConnector by sending the frameName
                AppletConnector ac = mfa.get(((String)list.getSelectedValue()).substring(0,((String)list.getSelectedValue()).lastIndexOf(" ")));

                // if ac is still active, call sendToApplet
                if (ac != null) {
                    // use OpenUrl like this:
                    // ac.sendToApplet("OpenURL", "http://www.yahoo.de", "_self");
                    ac.sendToApplet("OpenURL", url.getText(), (String) target.getSelectedItem());
                }
                else
                {
   	                AlertBox a = new AlertBox(containerFrame, new String[] {"Open URL failed: "+url.getText(),"","Please select a browser window or frame name from the list.","If no names are listed, please start a browser, set scone as proxy and load a page."});
				}
            }
        }
        );

        toFront = new JButton("Bring To Front");
        toFront.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //
                // That way you call the applet's bringToFront function
                //
                // get a reference of FrameAccess
                // fa = FrameAccess.getInstance();
                // get a reference of AppletConnector by sending the frameName
                AppletConnector ac = mfa.get( ((String)list.getSelectedValue()).substring(0,((String)list.getSelectedValue()).lastIndexOf(" ")) );

                // if ac is still active, call sendToApplet
                if (ac != null) {
                    // using BringToFront, you don't need 2nd and 3rd parameter
                    // containerFrame.transferFocus();
                    ac.sendToApplet("BringToFront", "", "");
                }
                else
                {
   	                AlertBox a = new AlertBox(containerFrame, new String[] {"Bring to Front failed.","","Please select a browser window or frame name from the list."});
				}
            }
        }
        );

        blur = new JButton("Blur Window");
        blur.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // That way you call the applet's blurBrowser function
                // fa = FrameAccess.getInstance();
                AppletConnector ac = mfa.get( ((String)list.getSelectedValue()).substring(0,((String)list.getSelectedValue()).lastIndexOf(" ")) );
                if (ac != null) {
                    ac.sendToApplet("BlurBrowser", "", "");
                }
	            else
                {
   	                AlertBox a = new AlertBox(containerFrame, new String[] {"Blur Browser failed.","","Please select a browser window or frame name from the list."});
				}
            }
        }
        );

        close = new JButton("Close Window");
        close.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // That way you call the applet's closeBrowser function
                // fa = FrameAccess.getInstance();
                AppletConnector ac = mfa.get( ((String)list.getSelectedValue()).substring(0,((String)list.getSelectedValue()).lastIndexOf(" ")) );

                if (ac != null) {
                    ac.sendToApplet("closeBrowser", "", "");  // Everything is converted to lowercase...
                }
	            else
                {
   	                AlertBox a = new AlertBox(containerFrame, new String[] {"Close Browser failed.","","Please select a browser window or frame name from the list."});
				}
            }
        }
        );

        test = new JButton("Any Function: e.g. move Browser");
        test.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // That way you call any javaScript function in the browser...
                // fa = FrameAccess.getInstance();
                AppletConnector ac = mfa.get( ((String)list.getSelectedValue()).substring(0,((String)list.getSelectedValue()).lastIndexOf(" ")) );
                String command = "window.moveTo(240,0); window.resizeTo(screen.width-240,screen.height-50);";

                if (ac != null) {
                    // The second parameter is the JavaScript-function to becalled in the browser...
                    ac.sendToApplet("anyFunction", command, "");
                }
	            else
                {
   	                AlertBox a = new AlertBox(containerFrame, new String[] {"anyFunction failed: "+command,"","Please select a browser window or frame name from the list."});
				}
            }
        }
        );

        // Add buttons, textfields ...
        pane = new JPanel();
        pane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        pane.setLayout(new GridLayout(7, 1, 3, 3));
        pane.add(url);
        pane.add(target);
        pane.add(openUrl);
        pane.add(toFront);
        pane.add(blur);
        pane.add(close);
        pane.add(test);

        containerFrame.getContentPane().add(listScrollPane, BorderLayout.SOUTH);
        containerFrame.getContentPane().add(pane, BorderLayout.CENTER);

        containerFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                mfa.stopNotifyMe();
            }
        }
        );

        containerFrame.pack();
        containerFrame.setVisible(true);

        mfa = new MyFrameAccess(this);  // ask FrameAccess to notify me by calling 
        mfa.notifyMe();               // my method FramesChanged()
    }

    /**
     * This method is called by FrameAccess everytime a new frame was added to
     * or removed from list of active frames. It updates the list in the gui.
     * <br>To be notified about frame list changes, this method has to be
     * implemented and FrameAccess's notifyMe method has to be called to 
     * register this class.
     *
     * @param contents A Set of parent frame names (if existing) concated with
     * frame names
     */ 
    public void framesChanged(Set contents) {
        Iterator myIterator;

        myIterator = contents.iterator();
        String frameString = "";

        listModel.clear();
        while (myIterator.hasNext()) {
            frameString = (String) myIterator.next();
            listModel.addElement(frameString + " " + mfa.getAccessObject(frameString).getNode().toString());
        }
        if (listModel.size() == 0) {
            listModel.addElement("No open frames");
        }
    }
}
