/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/


/**
 * Title:        slider<p>
 * Description:  <p>
 * Copyright:    Copyright (c) <p>
 * Company:      <p>
 * @author
 * @version 1.0
 */
package parser.slider;

import javax.swing.*;
import java.util.Vector;
import javax.swing.tree.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.Enumeration;
import javax.swing.text.*;

/****************************************
 * A contentualized, popup wordlist to be used by the parser
 */

public class PopupWordlist extends JFrame {

  private JList list;  //NOT CURRENTLY USED
  private JTree tree;
  private JScrollPane scrollpane;
  private JTextArea textfield;
  private StringBuffer searchTerm;

  public PopupWordlist() {
  }

  /**
   * constructor. requires a link to the text field, as well as a vector of vectors
   */
  public PopupWordlist(JTextArea intextfield, Vector words) {
    super();
    this.textfield = intextfield;
    tree = CreateTree(words);

    tree.addKeyListener(new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
          textfield.insert((String)((DefaultMutableTreeNode)tree.getLastSelectedPathComponent()).getUserObject() + " ", textfield.getCaretPosition());
          setVisible(false);
        }
        else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_DELETE) {
          searchTerm.deleteCharAt(searchTerm.length()-1);
          System.err.println(searchTerm.toString());
        }
        else if (!e.isActionKey()) {
          searchTerm.append(e.getKeyChar());
          System.err.println(searchTerm.toString());
          String s = selectionForKey(searchTerm.toString());
          if (!s.equals(""))
            setSelectedNode(s);
        }
      }
    });

    scrollpane = new JScrollPane( tree, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                  ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
    getContentPane().setLayout( new BorderLayout() );
    getContentPane().add( scrollpane , BorderLayout.CENTER );
  }


  /**
   * Creates a tree from a vector of vectors
   */
  private JTree CreateTree(Vector words) {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode child;

    for (int i = 0; i < words.size()-1; i++) {
      child = new DefaultMutableTreeNode(((Vector)words.elementAt(i)).elementAt(0));
      root.add(child);
      for (int j = 1; j < ((Vector)words.elementAt(i)).size(); j++) {
        child.add(new DefaultMutableTreeNode(((Vector)words.elementAt(i)).elementAt(j)));
      }

    }

    JTree t = new JTree(root);
    t.setRootVisible(false);
    t.setShowsRootHandles(true);
    return t;
  }

  /**
   * Shows the popup menu at the specified location
   */
  public void show(Component invoker, int x, int y) {
    this.setLocation(x,y);
    this.setSize(150,175);
    searchTerm = new StringBuffer("");
    this.setVisible(true);
  }

  public boolean isFocusTraversable() {
    return true;
  }


  /**
   * Returns the name of a node, based on what the user types. The node can then
   * be selected by calling setSelectedNode.
   */
  public String selectionForKey(String aKey) {
    String v;
    String pattern;

    Enumeration enum = ((DefaultMutableTreeNode)tree.getModel().getRoot()).depthFirstEnumeration();

    aKey = aKey.toLowerCase();

    DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
    DefaultMutableTreeNode current;
    TreePath path;

    while (enum.hasMoreElements()) {
      current = (DefaultMutableTreeNode)enum.nextElement();
      path = new TreePath(current.getPath());
      if (tree.isVisible(path)) {
        v = current.getUserObject().toString().toLowerCase();
        if ( v.length() > 0 && v.startsWith(aKey) )
          return current.getUserObject().toString();
        }
    }
    return "";
  }

  /**
   * Selects a node based on str.
   */
  public void setSelectedNode(String str) {
    DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
    Enumeration enum = root.depthFirstEnumeration();

    while(enum.hasMoreElements()) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode)enum.nextElement();
        String name = node.getUserObject().toString();
        if (str.equals(name)) {
          TreePath path = new TreePath(node.getPath());
          if (tree.isVisible(path)) {
            tree.setSelectionRow(tree.getRowForPath(path));
            tree.scrollPathToVisible(path);
          }
        }
    }
  }
}
