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


namespace MySQL.Grt.Db
{
	public class RecordsetModel : GrtListModel
	{
		/// <summary>
		/// Constructor that initializes the model with the given objects
		/// </summary>
		/// <param name="TreeView">The TreeViewAdv control this model belongs to</param>
		/// <param name="GrtTree">The GRT tree this model belongs to</param>
		/// <param name="NodeStateIcon">The NodeStateIcon NodeControl that displays the icon</param>
		public RecordsetModel(TreeViewAdv listView, Recordset grtList)
			: base(listView, grtList)
		{
      for (int columnIndex = 0, columnCount = grtList.field_count(); columnIndex < columnCount; ++columnIndex)
      {
        TreeColumn column = new TreeColumn(grtList.field_name(columnIndex), 100);
        column.Sortable = true;//! no effect (only visual marks). seems because of virtual mode.
        listView.Columns.Add(column);

        NodeTextBox nc = new NodeTextBox();
        nc.EditEnabled = false;//! to be editable
        nc.ParentColumn = column;
        nc.DataPropertyName = string.Format("{0}", columnIndex);
        nc.VirtualMode = true;
        nc.ValueNeeded += new EventHandler<NodeControlValueEventArgs>(ValueNeeded);
        listView.NodeControls.Add(nc);
      }
    }

		/// <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>();
      for (int i = 0, count = grtList.count(); i < count; i++)
			{
				NodeId nodeId = grtList.get_node(i);
				GrtListNode node;
				string value;
				grtList.get_field(nodeId, 0, out value);
				node = new GrtListNode(value, nodeId, null, this);
				items.Add(node);
			}
			return items;
		}

    #region event handlers
    /// <summary>
    /// Event handler that gets the value for the 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)
          return;

        NodeTextBox nc = sender as NodeTextBox;
        if (null == nc)
          return;

        int index= Int32.Parse(nc.DataPropertyName);
        string value;
        grtList.get_field(node.NodeId, index, out value);
        e.Value = value;
      }
    }
    #endregion

	}
}
