using System;
using System.Windows.Forms;

namespace CareFusion.ITSystemSimulator.Gui.Pages.Utils
{
    /// <summary>
    /// Source: https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-host-controls-in-windows-forms-datagridview-cells?redirectedfrom=MSDN
    /// </summary>
    public class CalendarColumn : DataGridViewColumn
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public CalendarColumn() : base(new CalendarCell())
        {
        }

        /// <summary>
        /// Gets or sets the Cell template property.
        /// </summary>
        public override DataGridViewCell CellTemplate
        {
            get => base.CellTemplate;
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
                {
                    throw new InvalidCastException("Must be a CalendarCell");
                }
                base.CellTemplate = value;
            }
        }
    }

    /// <summary>
    /// Derived custom calendar cell class.
    /// </summary>
    public class CalendarCell : DataGridViewTextBoxCell
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public CalendarCell()
            : base()
        {
            // Use the short date format.
            this.Style.Format = "d";
        }

        /// <summary>
        /// Initialize Editing Control.
        /// </summary>
        /// <param name="rowIndex">Row index</param>
        /// <param name="initialFormattedValue">Initial formatted value</param>
        /// <param name="dataGridViewCellStyle">DataGridView Cell Style</param>
        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                dataGridViewCellStyle);
            CalendarEditingControl ctl =
                DataGridView.EditingControl as CalendarEditingControl;
            // Use the default row value when Value property is null.
            if (this.Value == null)
            {
                ctl.Value = (DateTime)this.DefaultNewRowValue;
            }
            else
            {
                ctl.Value = (DateTime)this.Value;
            }
        }

        /// <summary>
        /// Edit type property.
        /// </summary>
        public override Type EditType => typeof(CalendarEditingControl);

        /// <summary>
        /// Value type property.
        /// </summary>
        public override Type ValueType => typeof(DateTime);

        /// <summary>
        /// Default new row value property.
        /// </summary>
        public override object DefaultNewRowValue => DateTime.Now;
    }

    /// <summary>
    /// Calendar Editing Control class.
    /// </summary>
    class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
    {
        private DataGridView _dataGridView;
        private bool _valueChanged = false;
        private int _rowIndex;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public CalendarEditingControl()
        {
            this.Format = DateTimePickerFormat.Short;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlFormattedValue property.
        /// </summary>
        public object EditingControlFormattedValue
        {
            get => Value.ToShortDateString();
            set
            {
                if (value is String)
                {
                    try
                    {
                        // This will throw an exception of the string is
                        // null, empty, or not in the format of a date.
                        this.Value = DateTime.Parse((String)value);
                    }
                    catch
                    {
                        // In the case of an exception, just use the
                        // default value so we're not left with a null value.
                        this.Value = DateTime.Now;
                    }
                }
            }
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        /// </summary>
        /// <param name="context">DataGridView Data Error Context</param>
        /// <returns>Editing Control Formatted Value</returns>
        public object GetEditingControlFormattedValue(
            DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        /// </summary>
        /// <param name="dataGridViewCellStyle">DataGridView Cell Style</param>
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
            this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
            this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlRowIndex property.
        /// </summary>
        public int EditingControlRowIndex
        {
            get => _rowIndex;
            set => _rowIndex = value;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlWantsInputKey method.
        /// </summary>
        /// <param name="key">The key</param>
        /// <param name="dataGridViewWantsInputKey">Boolean if DataGridView wants an input key or not.</param>
        /// <returns></returns>
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return !dataGridViewWantsInputKey;
            }
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit method.
        /// </summary>
        /// <param name="selectAll">Boolean if needs to select all</param>
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.RepositionEditingControlOnValueChange property.
        /// </summary>
        public bool RepositionEditingControlOnValueChange => false;

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlDataGridView property.
        /// </summary>
        public DataGridView EditingControlDataGridView
        {
            get => _dataGridView;
            set => _dataGridView = value;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlValueChanged property.
        /// </summary>
        public bool EditingControlValueChanged
        {
            get => _valueChanged;
            set => _valueChanged = value;
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingPanelCursor property.
        /// </summary>
        public Cursor EditingPanelCursor => base.Cursor;

        /// <summary>
        /// Handle OnValueChanged override event.
        /// </summary>
        /// <param name="eventargs">Event arguments</param>
        protected override void OnValueChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell have changed.
            _valueChanged = true;
            this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
            base.OnValueChanged(eventargs);
        }
    }
}