using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using MySQL.Grt;

namespace MySQL.Utilities
{
  public class GrtGridModel
  {
    DataGridView gridView;
    GridModel gridModel;
    bool refreshing = false;
    DataGridViewColumn[] columns;

    public GrtGridModel(DataGridView gridView, GridModel gridModel)
    {
      this.gridView = gridView;
      this.gridModel = gridModel;

      gridView.VirtualMode = true;
      gridView.CellValueNeeded += new DataGridViewCellValueEventHandler(gridView_CellValueNeeded);
      gridView.CellValuePushed += new DataGridViewCellValueEventHandler(gridView_CellValuePushed);
      gridView.NewRowNeeded += new DataGridViewRowEventHandler(gridView_NewRowNeeded);
      gridView.RowsRemoved += new DataGridViewRowsRemovedEventHandler(gridView_RowsRemoved);
    }

    public void UpdateGridView()
    {
      refreshing = true;

      columns= new DataGridViewColumn[gridModel.get_column_count()];

      for (int i= 0; i < gridModel.get_column_count(); i++)
      {
        DataGridViewTextBoxColumn column= new DataGridViewTextBoxColumn();

        column.HeaderText= gridModel.get_column_caption(i);
        column.Name= column.HeaderText;

        columns[i]= column;
      }

      gridView.Columns.Clear();
      gridView.Columns.AddRange(columns);
      gridView.AutoSizeColumnsMode= DataGridViewAutoSizeColumnsMode.AllCells;
      gridView.RowCount= gridModel.count()+1;

      refreshing = false;

      gridView.Refresh();
    }


    void gridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
    {
      if (refreshing) return;

      for (int i = 0; i < e.RowCount; i++)
        gridModel.delete_node(new NodeId(e.RowIndex));
    }


    void gridView_NewRowNeeded(object sender, DataGridViewRowEventArgs e)
    {
      if (refreshing) return;

      e.Row.Resizable = DataGridViewTriState.False;
    }

    void gridView_CellValuePushed(object sender, DataGridViewCellValueEventArgs e)
    {
      if (e.Value != null && !refreshing)
      {
        if (!gridModel.set_convert_field(new NodeId(e.RowIndex), e.ColumnIndex, (String)e.Value))
        {
          //String tmp;
          //gridModel.get_field(new NodeId(e.RowIndex), e.ColumnIndex, out tmp);
          //e.Value= tmp;
        }

        gridView.Refresh();
      }
    }

    void gridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
    {
      String value;

      gridModel.get_field(new NodeId(e.RowIndex), e.ColumnIndex, out value);

      e.Value = value;
    }

    
  }
}
