using System;
using System.Globalization;
using System.Windows.Forms;
using Ebel.Hardware.Communications;

namespace HwComWrapperNETGui.UserControls
{
    public partial class TerminationInfoControl : UserControl
    {
        #region Constructors and Destructors

        public TerminationInfoControl()
        {
            this.InitializeComponent();
            this.comboBoxTermination.DataSource = Enum.GetNames(typeof(ConfigStateRequested));
            this.comboBoxTermination.SelectedIndex = 0;
        }

        #endregion

        #region Public Methods

        public TerminationConfig GetTerminationConfig()
        {
            var terminationConfig = new TerminationConfig();
            foreach (ListViewItem listViewItem in this.listViewTerminationInfo.Items)
            {
                terminationConfig.AddTermInfo(
                    new TermInfo(
                        Convert.ToByte(listViewItem.SubItems[0].Text),
                        (ConfigState)Enum.Parse(typeof(ConfigStateRequested), listViewItem.SubItems[1].Text)));
            }

            return terminationConfig;
        }

        #endregion

        #region Methods

        private void OnAddTerminationInfoClicked(object sender, EventArgs e)
        {
            if (this.listViewTerminationInfo.Items.Count >= 255)
            {
                MessageBox.Show("Maximum number of termination infos reached.", "Maximum reached", MessageBoxButtons.OK);
                return;
            }

            var listViewItem =
                new ListViewItem(
                    new[] { this.numericUpDownChannelID.Value.ToString(CultureInfo.InvariantCulture), this.comboBoxTermination.SelectedItem.ToString() });

            this.listViewTerminationInfo.Items.Add(listViewItem);
            this.labelNumberOfInfos.Text = this.listViewTerminationInfo.Items.Count.ToString(CultureInfo.InvariantCulture);
        }

        private void OnRemoveTerminationInfoClicked(object sender, EventArgs e)
        {
            foreach (ListViewItem listViewItem in this.listViewTerminationInfo.SelectedItems)
            {
                this.listViewTerminationInfo.Items.Remove(listViewItem);
            }

            this.labelNumberOfInfos.Text = this.listViewTerminationInfo.Items.Count.ToString(CultureInfo.InvariantCulture);
        }
        
        #endregion
    }
}