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

using System;
using System.Drawing;
using System.Windows.Forms;

namespace EhLib
{
  class DateTimeBoxEhManager
  {
    #region static fields
    private static DateTimeBoxEhManager _defaultManager;
    #endregion static fields

    public DateTimeBoxEhManager()
    {
    }

    public static DateTimeBoxEhManager DefaultManager
    {
      get
      {
        if (_defaultManager == null)
          _defaultManager = new DateTimeBoxEhManager();
        return _defaultManager;
      }
      set
      {
        _defaultManager = value;
      }
    }

    #region methods
    public virtual void InEditButtonDownDefaultAction(DateTimeBoxEh dateTimeBox, EditItem inEditControl, DownEventArgs e)
    {
      DropDownCalendar ddForm = new DropDownCalendar();

      if (dateTimeBox.Value.HasValue)
        ddForm.Value = dateTimeBox.Value.Value;
      else
        ddForm.Value = DateTime.Today;
      //ddForm.ReadOnly = dateTimeBox.ReadOnly;

      Control buttonControl = inEditControl.InEditWinControl;
      Rectangle buttonScreenRect = buttonControl.RectangleToScreen(buttonControl.ClientRectangle);
      ddForm.CreateHandle();
      ddForm.PerformLayout();


      ddForm.ExecuteNomodal(
        dateTimeBox.RectangleToScreen(new Rectangle(new Point(0, 0), dateTimeBox.Size)),
        DropDownAlign.Left,
        InEditButtonDownDropDownFormCloseHandler,
        dateTimeBox,
        buttonScreenRect
        );

      e.Handled = true;
    }

    protected virtual void InEditButtonDownDropDownFormCloseHandler(object sender, DropDownFormCloseEventArgs e)
    {
      DropDownCalendar dropDownCalendar = (DropDownCalendar)sender;
      DateTimeBoxEh dateTimeBoxEh = (DateTimeBoxEh)(dropDownCalendar.MasterControl);
      dateTimeBoxEh.IgnoreMouseScreenRectPressed = e.IgnoreMouseScreenRectPressed;

      if (e.CloseResult == DialogResult.OK)
      {
        if (dateTimeBoxEh.Value.HasValue)
        {
          DateTime dateValue = dateTimeBoxEh.Value.Value;
          dateTimeBoxEh.Value = dropDownCalendar.Value.Date + dateValue.TimeOfDay;
        }
        else
        {
          dateTimeBoxEh.Value = dropDownCalendar.Value.Date;
        }
      }

    }
    #endregion methods
  }

}
