using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using Aga.Controls.Tree;
using Aga.Controls.Tree.NodeControls;
using MySQL.Grt;
using MySQL.Utilities;


namespace MySQL.Grt
{
  /// <summary>
  /// A generic GRT tree model class implementing the general case for a GrtListModel
  /// </summary>
  public class SimpleGrtListModel : GrtListModel, IToolTipProvider
  {
    protected class ColumnContent
    {
      public bool editable;
      public NodeControl control;
      public int index;
    };

    protected List<ColumnContent> columns = new List<ColumnContent>();

    /// <summary>
    /// The constructor that has to be overwritten in the derived model classes
    /// </summary>
    /// <param name="TreeView">The TreeViewAdv control this model is used for</param>
    /// <param name="GrtList">The GRT list this model is representing</param>
    public SimpleGrtListModel(TreeViewAdv ListView, MySQL.Grt.ListModel GrtList, bool DynamicContextMenu)
      : base(ListView, GrtList, DynamicContextMenu)
    {
      grtList = GrtList;
      listView = ListView;
    }

    public SimpleGrtListModel(TreeViewAdv ListView, MySQL.Grt.ListModel GrtList, NodeIcon nodeIcon, bool DynamicContextMenu)
      : base(ListView, GrtList, nodeIcon, DynamicContextMenu)
    {
      grtList = GrtList;
      listView = ListView;
    }


    public void AddColumn(NodeTextBox treeControl, int grtIndex, bool editable)
    {
      ColumnContent column = new ColumnContent();
      column.editable = editable;
      column.index = grtIndex;
      column.control = treeControl;

      treeControl.VirtualMode = true;
      treeControl.DataPropertyName = "Text";
      treeControl.ValueNeeded += new EventHandler<NodeControlValueEventArgs>(ValueNeeded);
      if (editable)
      {
        treeControl.EditEnabled = true;
        treeControl.ValuePushed += new EventHandler<NodeControlValueEventArgs>(ValuePushed);
        if (treeControl is AdvNodeTextBox)
          ((AdvNodeTextBox)treeControl).EditorInitialize += new EditorInitializeEventHandler(EditorInitialize);

      }
      else
        treeControl.EditEnabled = false;

      columns.Add(column);
    }


    public override void DetachEvents()
    {
      base.DetachEvents();

      foreach (ColumnContent column in columns)
      {
        NodeTextBox node = column.control as NodeTextBox;
        node.ValueNeeded -= ValueNeeded;
        if (column.editable)
        {
          if (node != null)
          {
            node.ValuePushed -= ValuePushed;

            if (node is AdvNodeTextBox)
              ((AdvNodeTextBox)node).EditorInitialize -= EditorInitialize;
          }
        }
      }
      columns = null;
    }

    /// <summary>
    /// Returns a node list of all child nodes of a given parent node
    /// </summary>
    /// <param name="treePath">The path of the parent node</param>
    /// <returns>The list of child nodes for the given parent path node</returns>
    public override System.Collections.IEnumerable GetChildren(TreePath treePath)
    {
      //List<GrtListNode> items = new List<GrtListNode>();

      // Get count but add the additional row for new columns
      int count = grtList.count();
      for (int i = 0; i < count; i++)
      {
        NodeId nodeId = grtList.get_node(i);
        GrtListNode node;
        string caption;

        grtList.get_field(nodeId, columns[0].index, out caption);

        node = new GrtListNode(caption, nodeId, null, this);

        yield return node;
      }
    }

    public String GetRowAsText(TreeNodeAdv treeNode)
    {
      string rowText = "";

      if (treeNode != null && treeNode.Tag != null)
      {
        GrtListNode node = treeNode.Tag as GrtListNode;

        if (node != null)
        {
          foreach (ColumnContent column in columns)
          {
            string caption;

            grtList.get_field(node.NodeId, column.index, out caption);

            if (rowText.Equals(""))
              rowText = caption;
            else
              rowText += " | " + caption;
          }
        }
      }

      return rowText;
    }

    public void EnableTooltips()
    {
      listView.DefaultToolTipProvider = this;
    }

    #region event handlers
    /// <summary>
    /// Event handler that gets the caption for the value column
    /// </summary>
    /// <param name="sender">The object triggering the event</param>
    /// <param name="e">The event parameter</param>
    private void ValueNeeded(object sender, NodeControlValueEventArgs e)
    {
      if (e.Node != null && e.Node.Tag != null)
      {
        GrtListNode node = e.Node.Tag as GrtListNode;

        if (node != null)
        {
          foreach (ColumnContent column in columns)
          {
            if (sender == column.control)
            {
              string caption;

              grtList.get_field(node.NodeId, column.index, out caption);

              e.Value = caption;
              break;
            }
          }
        }
      }
    }


    private void ValuePushed(object sender, NodeControlValueEventArgs e)
    {
      if (e.Node != null && e.Node.Tag != null)
      {
        GrtListNode node = e.Node.Tag as GrtListNode;

        if (node != null)
        {
          foreach (ColumnContent column in columns)
          {
            if (sender == column.control)
            {
              NodeTextBox tnode = column.control as NodeTextBox;

              grtList.set_convert_field(node.NodeId, column.index, e.Value as String);
              break;
            }
          }

          // save selcted node
          int selected= -1;
          if (node != null && listView.SelectedNode!=null)
            selected = listView.SelectedNode.Index;

          RefreshModel();

          if (selected >= 0)
            listView.SelectedNode = listView.Root.Children[selected];
        }
      }
    }


    private void EditorInitialize(object sender, EditorInitializeEventArgs e)
    {
      if (sender is AdvNodeTextBox)
      {
        TextBox textBox = e.Editor as TextBox;
        if (textBox != null)
        {
          textBox.KeyDown += new KeyEventHandler(textBox_KeyDown);//LLL
        }
      }
    }


    void textBox_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Tab || e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
      {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
          AdvNodeTextBox c = textBox.Tag as AdvNodeTextBox;
          if (c != null)
          {
            // Remember current index
            int selIndex = 0;
            if (listView.SelectedNode != null)
              selIndex = listView.SelectedNode.Index;

            c.EndEdit(true);

            e.Handled = true;
          }
        }
      }
    }
    #endregion
  
    #region IToolTipProvider Members

    public string  GetToolTip(TreeNodeAdv node, NodeControl nodeControl)
    {
      if (node != null && node.Tag != null)
      {
        GrtListNode lnode = node.Tag as GrtListNode;
        int c= 0;

        foreach (ColumnContent column in columns)
        {
          if (column.control == nodeControl)
          {
            c= column.index;
            break;
          }
        }

        return grtList.get_field_description(lnode.NodeId, c);
      }
      return "";
    }

    #endregion

}
}
