using System;
using System.Windows.Forms;

namespace CareFusion.ITSystemSimulator.Gui.Pages.Utils
{
    /// <summary>
    /// Custom DropDownComboBoxColumn
    /// </summary>
    public class DropDownComboBoxColumn : DataGridViewColumn
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public DropDownComboBoxColumn() : base(new DropDownComboBoxCell())
        {
        }

        /// <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 DropDownComboBoxCell.
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(DropDownComboBoxCell)))
                {
                    throw new InvalidCastException("Must be a DropDownComboBoxCell");
                }
                base.CellTemplate = value;
            }
        }

        public ComboBoxStyle DropDownStyle { get; set; }
    }

    /// <summary>
    /// Derived custom DropDownComboBox cell class.
    /// </summary>
    public class DropDownComboBoxCell : DataGridViewTextBoxCell
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public DropDownComboBoxCell()
            : base()
        {
        }

        /// <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);
            DropDownComboBoxEditingControl ctl =
                DataGridView.EditingControl as DropDownComboBoxEditingControl;
            // Use the default row value when Value property is null.
            if (this.Value == null)
            {
                ctl.Text = this.DefaultNewRowValue.ToString();
            }
            else
            {
                ctl.Text = this.Value.ToString();
            }
        }

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

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

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

    /// <summary>
    /// DropDown ComboBox Editing Control class.
    /// </summary>
    class DropDownComboBoxEditingControl : ComboBox, IDataGridViewEditingControl
    {
        private DataGridView _dataGridView;
        private bool _valueChanged = false;
        private int _rowIndex;

        /// <summary>
        /// Default constructor.
        /// </summary>
        public DropDownComboBoxEditingControl()
        {
        }

        /// <summary>
        /// Implements the IDataGridViewEditingControl.EditingControlFormattedValue property.
        /// </summary>
        public object EditingControlFormattedValue
        {
            get => Text;
            set
            {
                if (value is string)
                {
                    try
                    {
                        this.Text = value.ToString();
                    }
                    catch
                    {
                        // In the case of an exception, just use the
                        // default value so we're not left with a null value.
                        this.Text = string.Empty;
                    }
                }
            }
        }

        /// <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.ForeColor = dataGridViewCellStyle.ForeColor;
            this.BackColor = 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 ComboBox 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:
                case Keys.F4:
                    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)
        {
            DropDownComboBoxColumn col = _dataGridView.Columns[_dataGridView.CurrentCell.ColumnIndex] as DropDownComboBoxColumn;
            if (col == null)
            {
                throw new InvalidCastException("Must be in a DropDownComboBoxColumn");
            }
            DropDownStyle = col.DropDownStyle;

            // (If you don't explicitly set the Text then the current value is
            // always replaced with one from the drop-down list when edit begins.)
            Text = _dataGridView.CurrentCell.Value as string;
            SelectAll();
        }

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