//------------------------------------------------------------------------------
// <copyright file=”*.cs” company=”EhLib Team”>
//     Copyright (c) 2017-2018 Dmitry V. Bolshakov   
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Forms.Design.Behavior;
using System.Collections.Generic;
using System.Drawing.Drawing2D;

namespace EhLib.Design
{

  [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
  public class DataGridDesigner : DataAxisGridDesigner, IDataGridDesigner
  {
    private DesignerActionListCollection actionLists;
    //private Adorner titleAdorner;

    //internal DesignerVerb globalVerb;

    //private DesignerVerb addSuperTitleVerb;
    //private DesignerVerb deleteSuperTitleVerb;
    //private DesignerVerb removeFromSuperTitleVerb;

    private List<DesignerVerb> subTitlesMenuList = new List<DesignerVerb>();

    internal ISelectionService SelService;
    internal Point GridMouseDownPos = Point.Empty;

    #region constructor
    public DataGridDesigner()
    {

    }

    public override void Initialize(IComponent component)
    {
      base.Initialize(component);
      SelService = (ISelectionService)GetService(typeof(ISelectionService));
      if (SelService != null)
      {
        SelService.SelectionChanged += SelService_SelectionChanged;
        SelService.SelectionChanging += SelService_SelectionChanging;
      }

      Grid.DataGridDesigner = this;
      Grid.OrderedColumnsListChanged += Grid_OrderedColumnsListChanged;

      //titleAdorner = new Adorner();
      //Debug.Assert(this.BehaviorService != null, "this.BehaviorService != null");
      //this.BehaviorService.Adorners.Add(titleAdorner);
      //titleAdorner.Glyphs.Add(new GridTitleGlyph(BehaviorService, Control, this));

    }

    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        Grid.DataGridDesigner = null;
        Grid.OrderedColumnsListChanged -= Grid_OrderedColumnsListChanged;

        if (SelService != null)
        {
          SelService.SelectionChanged -= SelService_SelectionChanged;
          SelService.SelectionChanging -= SelService_SelectionChanging;
          //MessageBox.Show("DataGridDesigner.Dispose");
        }

        //if (titleAdorner != null)
        //{
        //  BehaviorService b = BehaviorService;
        //  if (b != null)
        //  {
        //    b.Adorners.Remove(titleAdorner);
        //  }
        //}
      }

      base.Dispose(disposing);
    }
    #endregion

    internal new DataGridEh Grid
    {
      get { return this.Component as DataGridEh; }
    }

    public override string PropAxisBarName
    {
      get { return "Column"; }
    }

    public override string PropAxisBarsName
    {
      get { return "Columns"; }
    }

    public override Type StaticPropBarCollectionType
    {
      get { return typeof(DataGridStaticColumnCollection); }
    }

    public override ICollection AssociatedComponents
    {
      get
      {
        //return base.AssociatedComponents;
        ArrayList items = new ArrayList();
        //items.Add(Grid.StaticColumns);
        //items.Add(Grid.SearchBox);
        foreach(var c in Grid.StaticColumns)
          items.Add(c);
        //items.Add(Grid.HorzScrollBar);
        return items;
      }
    }

    public override DesignerVerbCollection Verbs
    {
      get
      {
        //var result = base.Verbs;
        DesignerVerbCollection dvc = new DesignerVerbCollection();
        //dvc.Add(new DesignerVerb("Создать testEvent", ConnectEvent));
        dvc.Add(new DesignerVerb("About EhLib.WinForms", ShowAboutDialog));
        return dvc;
      }
    }

    public override DesignerActionListCollection ActionLists
    {
      get
      {
        if (actionLists == null)
        {
          actionLists = new DesignerActionListCollection();
          actionLists.Add(new DataAxisGridChooseDataSourceActionList(this));
          actionLists.Add(new DataAxisGridActionList(this));
          actionLists.Add(new DataAxisGridPropertiesActionList(this));
          actionLists.AddRange(base.ActionLists);
        }
        return actionLists;
      }
    }

    // IDataGridDesigner
    public virtual void PaintCellDesignData(DataGridEh grid, Graphics graphics, int col, int row, Rectangle rect, BasePaintCellStates state)
    {
      CellAreaType cellAreaType = grid.GetCellAreaTypeByColRow(col, row);
      if (cellAreaType.VertType == DataGridCellAreaVertType.Title)
      {
        int colIndex = grid.BaseToDataColIndex(col);
        if (colIndex < 0) return;
        DataGridColumn column = grid.VisibleColumns[colIndex];
        if ((SelService != null) && (column != null))
        {
          if (SelService.GetComponentSelected(column))
          { 
            Rectangle paintRect = rect;
            paintRect.Inflate(-2, -2);
            using (Pen pen = new Pen(Color.Black, 1))
            {
              pen.DashStyle = DashStyle.Dot;
              graphics.DrawRectangle(pen, paintRect);
            }
          }
        }
      }
      else if (cellAreaType.VertType == DataGridCellAreaVertType.Footer && 
                 (cellAreaType.HorzType == DataGridCellAreaHorzType.Data || 
                  cellAreaType.HorzType == DataGridCellAreaHorzType.Contra)
              )
      {
        int localColIndex;
        int localRowIndex;
        DataGridBaseCellMan cell = (DataGridBaseCellMan)grid.CellByColRow(col, row, out localColIndex, out localRowIndex);
        if (localColIndex >= grid.VisibleColumns.Count) return;
        DataGridColumn column = grid.VisibleColumns[localColIndex];
        if (localRowIndex < column.Footer.Items.Count)
        {
          int shift = 0;
          DataGridColumnFooterItem footerItem = column.Footer.Items[localRowIndex];

          if (SelService.GetComponentSelected(footerItem))
          {
            Rectangle paintRect = rect;
            paintRect = EhLibUtils.ChangeRectangle(paintRect, 1, 1, -3, -3);
            //paintRect.Inflate(-1, -1);
            using (Pen pen = new Pen(Color.Black, 1))
            {
              pen.DashStyle = DashStyle.Dot;
              graphics.DrawRectangle(pen, paintRect);
            }
            shift = 2;
          }

          graphics.DrawPolygon(new Pen(Color.Silver),
            new Point[] {
              new Point(rect.Right-7-shift, rect.Top+1+shift),
              new Point(rect.Right-2-shift, rect.Top+1+shift),
              new Point(rect.Right-2-shift, rect.Top+6+shift)
            });
        }
      }
    }

    public virtual void PaintSuperTitleCellDesignData(DataGridEh grid, DataGridSuperTitle superTitle, 
      Graphics graphics, Rectangle rect)
    {
      if (SelService.GetComponentSelected(superTitle))
      {
        Rectangle paintRect = rect;
        paintRect.Inflate(-2, -2);
        using (Pen pen = new Pen(Color.Black, 1))
        {
          pen.DashStyle = DashStyle.Dot;
          graphics.DrawRectangle(pen, paintRect);
        }
      }
    }

    public virtual void InteractiveSetColWidths(int colIndex, int newSize)
    {
      if (colIndex >= Grid.StartDataColIndex)
      {
        DataGridColumn column = Grid.VisibleColumns[colIndex - Grid.StartDataColIndex];

        column.Width = newSize;
        ComponentChanged(Grid);
      }
    }

    public virtual void InteractiveMoveColumn(int fromIndex, int toIndex)
    {
      ((IBaseGridControlInternal)Grid).MoveColumn(fromIndex, toIndex);

      //if (Grid.StaticColumns.Count != Grid.Columns.Count)
      //  throw (new InvalidOperationException(@"Can't move column when grid have dynamic columns"));
      //Grid.StaticColumns.SetColumnsOrder(Grid.ViewOrderedColumns);
      //ComponentChanged(Grid);
    }

    public virtual void GridMouseDown(MouseEventArgs e)
    {
      int index;
      int pos, ofs;
      BaseGridState state;

      GridMouseDownPos = e.Location;

      //BaseGridState state = Grid.CheckSizingState(e.X, e.Y);
      Grid.CalcSizingState(e.X, e.Y, out state, out index, out pos, out ofs);

      if (e.Button == MouseButtons.Left && state == BaseGridState.ColSizing)
      {
        Grid.Capture = true;
        if (Grid.Capture)
        {
          //MessageBox.Show("grid.StartColSizing");
          Grid.StartColSizing(index, e.X, e.Y, pos, ofs);
        }
        return;
      }

      Component hitTestComponent = GetHitTestComponent(e.Location);

      if (hitTestComponent != null)
      {
        if (e.Button == MouseButtons.Left)
        {
          ISelectionService selSrv = SelService;
          selSrv.SetSelectedComponents(new object[] { hitTestComponent });
        }
      }
    }

    public virtual void GridMouseUp(MouseEventArgs e)
    {
      Component hitTestComponent = GetHitTestComponent(e.Location);

      if (e.Button == MouseButtons.Right && hitTestComponent != null)
      {
        //menu.Show(control, new Point(control.Width, 0));

        IMenuCommandService service = (IMenuCommandService)GetService(typeof(IMenuCommandService));
        if (service != null)
        {
          Point screenMousePos = Grid.PointToScreen(e.Location);
          //AddGlobalMenu(service);
          service.ShowContextMenu(MenuCommands.SelectionMenu, screenMousePos.X, screenMousePos.Y);
          //RemoveGlobalMenu(service);
        }
      }
    }

    public virtual void GridMouseMove(MouseEventArgs e)
    {
      ((IBaseGridControlInternal)Grid).UpdateCursor(e);

      Component hitTestComponent = GetHitTestComponent(e.Location);

      if (hitTestComponent != null &&
          (hitTestComponent is DataGridSuperTitle || hitTestComponent is DataGridColumn) &&
          e.Button == MouseButtons.Left &&
          Grid.GridState == BaseGridState.Normal &&
          GridMouseDownPos != e.Location
         )
      {
        GridCoord cellHit = Grid.CalcCellCoordFromPoint(e.X, e.Y);

        Grid.StartColMoving(cellHit.X, cellHit.X, e.X, e.Y);
      }
    }

    // Other
    public override DataAxisGridPropertyBarsEditor CreatePropertyBarsEditor()
    {
      return new DataGridColumnsEditor(StaticPropBarCollectionType);
    }

    private void Grid_OrderedColumnsListChanged(object sender, EventArgs e)
    {
      if (!Grid.InInitialization && !((IDataAxisGridInternal)Grid).IsInEndInit())
      {
        //MessageBox.Show("Grid_OrderedColumnsListChanged");
        Grid.StaticColumns.SetColumnsOrder(Grid.ViewOrderedColumns);
        ComponentChanged(Grid);
      }
    }

    private void ComponentChanged(object component)
    {
      IComponentChangeService desTimeChangeService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
      if (desTimeChangeService != null)
      {
        desTimeChangeService.OnComponentChanged(component, null, null, null);
        //desTimeChangeService.OnComponentChanged(this, null, null, null);
      }
    }

    public override void DoDefaultAction()
    {
      ShowEditColumnsDialog();
    }

    public void ShowEditColumnsDialog()
    {
      DataGridColumnsEditor ce = new DataGridColumnsEditor(typeof(DataGridStaticColumnCollection));

      PropertyDescriptor propDesc = TypeDescriptor.GetProperties(Grid)["StaticColumns"];
      DialogWindowsFormsEditorService internalSrv = new DialogWindowsFormsEditorService(Grid, propDesc);

      ce.EditValue(internalSrv, internalSrv, Grid.StaticColumns);
    }

    internal new object GetService(Type serviceType)
    {
      return base.GetService(serviceType);
    }

    //internal void AddGlobalMenu(IMenuCommandService mcSerive)
    //{
    //  bool allSelIsMultiTitleProvider = false;
    //  ICollection sel = SelService.GetSelectedComponents();
    //  object selObject = null;
    //  DataGridSuperTitle parentSuperTitle = null;
    //  DataGridTitleNode parentNode = null;

    //  foreach (object o in sel)
    //  {
    //    IMultiTitleNodeProvider iNode = (o as IMultiTitleNodeProvider);
    //    DataGridTitleNode gridTitleNode = null;
    //    if (iNode != null)
    //    {
    //      gridTitleNode = iNode.GetNode();
    //      if (gridTitleNode != null)
    //        parentNode = gridTitleNode.Parent;
    //    }
    //    if (gridTitleNode != null &&
    //        gridTitleNode.Parent != Grid.Title.MultiTitle.Root &&
    //        gridTitleNode.Parent.NodeType == DataGridTitleNodeType.SuperTitle)
    //      parentSuperTitle = gridTitleNode.Parent.SuperTitle;
    //    break;
    //  }

    //  foreach (object o in sel)
    //  {
    //    if (sel.Count == 1)
    //      selObject = o;

    //    IMultiTitleNodeProvider iNode = (o as IMultiTitleNodeProvider);
    //    if (iNode == null)
    //    {
    //      allSelIsMultiTitleProvider = false;
    //      parentSuperTitle = null;
    //      parentNode = null;
    //      break;
    //    }
    //    else
    //    {
    //      DataGridTitleNode gridTitleeNode = iNode.GetNode();
    //      if (gridTitleeNode != null && gridTitleeNode.Parent != parentNode)
    //        parentNode = null;
    //      if (gridTitleeNode != null && gridTitleeNode.Parent.SuperTitle != parentSuperTitle)
    //        parentSuperTitle = null;
    //      allSelIsMultiTitleProvider = true;
    //    }
    //  }

    //  IMenuCommandService mcs;

    //  if (mcSerive != null)
    //    mcs = mcSerive;
    //  else
    //    mcs = (IMenuCommandService)Component.Site.GetService(typeof(IMenuCommandService));

    //  //// Добавляем меню
    //  //if (globalVerb == null)
    //  //  globalVerb = new DesignerVerb("Глобальное меню", OnGlobal1);
    //  //globalVerb.Visible = true;
    //  //globalVerb.Enabled = allSelIsCols;
    //  //globalVerb.Supported = true;
    //  //mcs.RemoveVerb(globalVerb);
    //  //mcs.AddVerb(globalVerb);

    //  // Delete SuperTitle Verb
    //  //string verbText;

    //  if (deleteSuperTitleVerb != null)
    //    mcs.RemoveVerb(deleteSuperTitleVerb);

    //  //if (selObject is DataGridSuperTitle)
    //  //  verbText = "Delete SuperTitle '" + ((DataGridSuperTitle)selObject).Text + "'";
    //  //else
    //  //  verbText = "Delete SuperTitle";

    //  deleteSuperTitleVerb = new DesignerVerb("Delete SuperTitle", DeleteSuperTitleHandler);
    //  deleteSuperTitleVerb.Visible = true;
    //  deleteSuperTitleVerb.Enabled = selObject is DataGridSuperTitle;
    //  deleteSuperTitleVerb.Supported = true;
    //  mcs.AddVerb(deleteSuperTitleVerb);

    //  // Add SuperTitle Verb
    //  if (addSuperTitleVerb == null)
    //    addSuperTitleVerb = new DesignerVerb("Add SuperTitle", AddSuperTitleHandler);
    //  addSuperTitleVerb.Visible = true;
    //  addSuperTitleVerb.Enabled = allSelIsMultiTitleProvider && Grid.Title.MultiTitle.Active;
    //  addSuperTitleVerb.Supported = true;
    //  mcs.RemoveVerb(addSuperTitleVerb);
    //  mcs.AddVerb(addSuperTitleVerb);


    //  // remove From SuperTitle Verb
    //  if (removeFromSuperTitleVerb != null)
    //  {
    //    mcs.RemoveVerb(removeFromSuperTitleVerb);
    //    removeFromSuperTitleVerb = null;
    //  }

    //  if (parentSuperTitle != null)
    //  {
    //    removeFromSuperTitleVerb = new DesignerVerb("Remove from \"" + parentSuperTitle.Text + "\"", MoveToSuperTitleHandler);
    //    removeFromSuperTitleVerb.Visible = true;
    //    removeFromSuperTitleVerb.Enabled = allSelIsMultiTitleProvider && Grid.Title.MultiTitle.Active;
    //    removeFromSuperTitleVerb.Supported = true;
    //    mcs.AddVerb(removeFromSuperTitleVerb);
    //  }

    //  if (Grid.Title.MultiTitle.Active)
    //  {
    //    ClearSubtitleMenuList(mcSerive);

    //    DataGridTitleNode node = Grid.Title.MultiTitle.GetFirst();
    //    while (node != null)
    //    {
    //      if (node.NodeType == DataGridTitleNodeType.SuperTitle)
    //      {
    //        DesignerVerb sbvVerb = new DesignerVerb("Move under \"" + node.SuperTitle.Text + "\"", MoveToSuperTitleHandler);

    //        sbvVerb.Visible = true;
    //        sbvVerb.Enabled = allSelIsMultiTitleProvider;
    //        sbvVerb.Supported = true;
    //        mcs.AddVerb(sbvVerb);

    //        subTitlesMenuList.Add(sbvVerb);
    //      }
    //      node = Grid.Title.MultiTitle.GetNext(node);
    //    }
    //  }
    //}

    //internal void RemoveGlobalMenu(IMenuCommandService mcSerive)
    //{
    //  //if (globalVerb != null)
    //  //  mcSerive.RemoveVerb(globalVerb);
    //  if (addSuperTitleVerb != null)
    //    mcSerive.RemoveVerb(addSuperTitleVerb);
    //  if (deleteSuperTitleVerb != null)
    //    mcSerive.RemoveVerb(deleteSuperTitleVerb);
    //}

    internal void ClearSubtitleMenuList(IMenuCommandService mcSerive)
    {
      foreach(DesignerVerb verb in subTitlesMenuList)
      {
        mcSerive.RemoveVerb(verb);
      }
      subTitlesMenuList.Clear();
    }

    protected override void OnContextMenu(int x, int y)
    {
      //System.Windows.Forms.MessageBox.Show("OnContextMenu(int x, int y)");
      //AddGlobalMenu(null);
      base.OnContextMenu(x, y);
      //System.Windows.Forms.MessageBox.Show("After OnContextMenu(int x, int y)");
    }

    //private void OnGlobal1(object sender, System.EventArgs e)
    //{
    //  System.Windows.Forms.MessageBox.Show(@"Вызвано меню Global1");
    //}

    private void DeleteSuperTitleHandler(object sender, System.EventArgs e)
    {
      ICollection sel = SelService.GetSelectedComponents();

      foreach (object o in sel)
      {
        DataGridSuperTitle sp = o as DataGridSuperTitle;
        if (sp != null)
        {
          sp.Dispose();
          return;
        }
      }

      IComponentChangeService chService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
      chService.OnComponentChanged(this, null, null, null);
    }

    private void AddSuperTitleHandler(object sender, System.EventArgs e)
    {
      ICollection sel = SelService.GetSelectedComponents();
      List<object> selList = new List<object>();


      foreach (object o in sel)
      {
        if ((o is DataGridColumn) || (o is DataGridSuperTitle))
        {
          selList.Add(o);
        }
        else
        {
          MessageBox.Show(@"The selected object is not DataGridColumn or DataGridSuperTitle");
          return;
        }
      }

      if (selList.Count == 0) return;

      int itemLevel = ((IMultiTitleNodeProvider)selList[0]).GetNode().Level;

      foreach (object o in selList)
      {
        DataGridTitleNode n = ((IMultiTitleNodeProvider)o).GetNode();
        if (n.Level != itemLevel)
        {
          MessageBox.Show(@"Not all selected nodes is on the same tree node level");
          return;
        }
      }

      IMultiTitleNodeProvider firstItem = (IMultiTitleNodeProvider)selList[0];

      string stTitleText = "SuperTitle";
      DialogResult result = EhLibUtils.InputBox("Name of title", "Enter text of title", ref stTitleText);
      if (result != DialogResult.OK) return;

      IDesignerHost host = (IDesignerHost)GetService(typeof(IDesignerHost));
      DataGridSuperTitle st = (DataGridSuperTitle)host.CreateComponent(typeof(DataGridSuperTitle));
      st.Text = stTitleText;
      //DataGridSuperTitle st = new DataGridSuperTitle()
      //{
      //  Text = stTitleText
      //};

      DataGridTitleNode node = firstItem.GetNode();

      Grid.Title.MultiTitle.TitleTree.BeginUpdate();
      int Index = node.Index;
      node.Parent.Subtitles.Insert(Index, st);

      //selList.Reverse();

      foreach (object o in selList)
      {
        st.Subtitles.MoveIn(st.Subtitles.Count, (IMultiTitleNodeProvider)o);
      }

      Grid.Title.MultiTitle.TitleTree.EndUpdate();

      IComponentChangeService chService = (IComponentChangeService)GetService(typeof(IComponentChangeService));
      chService.OnComponentChanged(this, null, null, null);

    }

    private void MoveToSuperTitleHandler(object sender, System.EventArgs e)
    {
    }

    private void ConnectEvent(object sender, EventArgs e)
    {
      MessageBox.Show(@"ConnectEvent: " + e.ToString());
    }

    private void ShowAboutDialog(object sender, EventArgs e)
    {
      FormAbout fa = new FormAbout();
      fa.ShowDialog();
    }

    private void SelService_SelectionChanged(object sender, EventArgs e)
    {
      Control.Invalidate();
//      MessageBox.Show("selService_SelectionChanged");
    }

    private void SelService_SelectionChanging(object sender, EventArgs e)
    {

    }

    protected override bool GetHitTest(Point point)
    {
      Point tpPoint = this.Control.PointToClient(point);

      if (Grid.GridState == BaseGridState.Normal)
      {
        BaseGridState state = Grid.CheckSizingState(tpPoint.X, tpPoint.Y);
        if (state == BaseGridState.ColSizing)
          return true;
      }

      GridCoord cellCoord = Grid.CalcCellCoordFromPoint(tpPoint.X, tpPoint.Y);
      Component hitTestComponent = GetHitTestComponent(tpPoint);
      if ((hitTestComponent != null) ||
          (cellCoord.X >= Grid.StartDataColIndex) && (cellCoord.Y == Grid.TitleRowIndex))
      {
        //        MessageBox.Show(cellCoord.X.ToString() +":"+ cellCoord.Y.ToString());
        return true;
      }

      return base.GetHitTest(point);
    }

    protected virtual Component GetHitTestComponent(Point point)
    {
      BaseGridState state = Grid.CheckSizingState(point.X, point.Y);
      if (state == BaseGridState.ColSizing)
        return null;

      GridCoord cellHit = Grid.CalcCellCoordFromPoint(point.X, point.Y);
      int dataColHit = cellHit.X - Grid.StartDataColIndex;
      if (cellHit.X >= Grid.StartDataColIndex &&
          dataColHit < Grid.VisibleColumns.Count)
      {
        DataGridColumn column = Grid.VisibleColumns[dataColHit];

        if (cellHit.Y == Grid.TitleRowIndex)
        {

          ISelectionService selSrv = SelService;

          if (Grid.Title.MultiTitle.Active)
          {
            DataGridBaseCellMan cell = (DataGridBaseCellMan)Grid.CellByColRow(cellHit.X, cellHit.Y);
            DataGridTitleCellMan titleCell = (cell as DataGridTitleCellMan);
            if (titleCell != null)
            {
              DataGridTitleNode tn = titleCell.GetMultiTitleNodeAtPos(point);
              if (tn != null)
              {
                if (tn.NodeType == DataGridTitleNodeType.ColumnTitle)
                  return tn.ColumnTitle.Column;
                else
                  return tn.SuperTitle;
              }
            }
          }
          else
          {
            if ((selSrv != null) && (column != null))
            {
              return column;
            }
          }
        }
        else if (cellHit.Y >= Grid.RowCount)
        {
          int localColIndex;
          int localRowIndex;
          DataGridBaseCellMan cell = (DataGridBaseCellMan)Grid.CellByColRow(cellHit.X, cellHit.Y, out localColIndex, out localRowIndex);
          if (localRowIndex < column.Footer.Items.Count)
          {
            return column.Footer.Items[localRowIndex];
          }
        }
      }
      return null;
    }

    internal static void ShowErrorDialog(IUIService uiService, Exception ex, Control dataGridView)
    {
      if (uiService != null)
      {
        uiService.ShowError(ex);
      }
      else
      {
        string message = ex.Message;
        if (string.IsNullOrEmpty(message))
        {
          message = ex.ToString();
        }
        MessageBox.Show(dataGridView, message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1, 0);
      }
    }

    internal static void ShowErrorDialog(IUIService uiService, string errorString, Control dataGridView)
    {
      if (uiService != null)
      {
        uiService.ShowError(errorString);
      }
      else
      {
        MessageBox.Show(dataGridView, errorString, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                MessageBoxDefaultButton.Button1, 0);
      }
    }

    protected override void OnSetCursor()
    {
      Point gridCurPos = Grid.PointToClient(Cursor.Position);

      Component hitTestComponent = GetHitTestComponent(gridCurPos);
      BaseGridState state = Grid.CheckSizingState(gridCurPos.X, gridCurPos.Y);
      if (state == BaseGridState.ColSizing)
      {
        Cursor.Current = Cursors.HSplit;
      }
      else if (hitTestComponent != null)
      {
        Cursor.Current = Cursors.Arrow;
      }
      else
      {
        base.OnSetCursor();
      }
    }

    protected override void OnMouseDragBegin(int x, int y)
    {
      base.OnMouseDragBegin(x, y);
    }

    protected override void OnMouseDragMove(int x, int y)
    {
      Component hitComponent = GetHitTestComponent(new Point(x, y));
      if (hitComponent != null)
        MessageBox.Show("Start Column Moving");
      else
        base.OnMouseDragMove(x, y);
    }

    private void WmMouseUp(ref Message m, MouseButtons button)
    {
      //int x = NativeMethods.SignedLOWORD(m.LParam);
      //int y = NativeMethods.SignedHIWORD(m.LParam);
      //Point mousePos = new Point(x, y);
      //Point screenMousePos = Grid.PointToScreen(mousePos);

      //Component hitTestComponent = GetHitTestComponent(mousePos);

      //if (Grid.GridState == BaseGridState.Normal &&
      //    hitTestComponent != null && 
      //    button == MouseButtons.Left)
      //{
      //  //ISelectionService selSrv = SelService;
      //  //selSrv.SetSelectedComponents(new object[] { hitTestComponent });
      //  EhLibUtils.DoNothing();
      //}
      //else if (button == MouseButtons.Right)
      //{
      //  //menu.Show(control, new Point(control.Width, 0));

      //  IMenuCommandService service = (IMenuCommandService)GetService(typeof(IMenuCommandService));
      //  if (service != null)
      //  {
      //    AddGlobalMenu(service);
      //    service.ShowContextMenu(MenuCommands.SelectionMenu, screenMousePos.X, screenMousePos.Y);
      //    RemoveGlobalMenu(service);
      //  }
      //}
      //else
      {
        base.WndProc(ref m);
      }
    }

    private void WmMouseDown(ref Message m, MouseButtons button)
    {
      //int x = NativeMethods.SignedLOWORD(m.LParam);
      //int y = NativeMethods.SignedHIWORD(m.LParam);
      //Point mousePos = new Point(x, y);

      //Component hitTestComponent = GetHitTestComponent(mousePos);

      //if (hitTestComponent != null)
      //{
      //  if (button == MouseButtons.Left)
      //  {
      //    ISelectionService selSrv = SelService;
      //    selSrv.SetSelectedComponents(new object[] { hitTestComponent });
      //  }
      //}
      //else
      {
        base.WndProc(ref m);
      }
    }

    private void WmMouseMove(ref Message m)
    {
      //MouseButtons buttons = Control.MouseButtons;
      //int x = NativeMethods.SignedLOWORD(m.LParam);
      //int y = NativeMethods.SignedHIWORD(m.LParam);
      //Point mousePos = new Point(x, y);

      //Component hitTestComponent = GetHitTestComponent(mousePos);

      //if (hitTestComponent != null &&
      //    buttons == MouseButtons.Left &&
      //    Grid.GridState == BaseGridState.Normal)
      //{
      //  GridCoord cellHit = Grid.CalcCellCoordFromPoint(x, y);

      //  Grid.StartColMoving(cellHit.X, cellHit.X, x, y);
      //}
      //else
      {
        base.WndProc(ref m);
      }
    }

    private void WmNCHitTest(ref Message m)
    {
      base.WndProc(ref m);
    }

    protected override void WndProc(ref Message m)
    {
      switch (m.Msg)
      {
        case NativeMethods.WM_MOUSEMOVE:
          WmMouseMove(ref m);
          break;
        case NativeMethods.WM_LBUTTONUP:
          WmMouseUp(ref m, MouseButtons.Left);
          break;
        case NativeMethods.WM_RBUTTONUP:
          WmMouseUp(ref m, MouseButtons.Right);
          break;
        case NativeMethods.WM_LBUTTONDOWN:
          WmMouseDown(ref m, MouseButtons.Left);
          break;
        case NativeMethods.WM_RBUTTONDOWN:
          WmMouseDown(ref m, MouseButtons.Right);
          break;
        case NativeMethods.WM_NCHITTEST:
          WmNCHitTest(ref m);
          break;

        default:
          base.WndProc(ref m);
          break;
      }
    }
  }

}
