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

namespace HwComWrapperNETGui.UserControls
{
    public partial class WakeupSleepInfoControl : UserControl
    {

        #region Constructors and Destructors

        public WakeupSleepInfoControl()
        {
            this.InitializeComponent();

            this.comboBoxSleep.DataSource = Enum.GetNames(typeof(ConfigStateRequested));
            this.comboBoxSleep.SelectedIndex = 0;
            this.comboBoxWakeup.DataSource = Enum.GetNames(typeof(ConfigStateRequested));
            this.comboBoxWakeup.SelectedIndex = 0;
        }

        #endregion

        public WakeupSleepConfig GetWakeupSleepConfig()
        {
            var wakeupSleepConfig = new WakeupSleepConfig();
            foreach (ListViewItem listViewItem in this.listViewWUPSleepInfo.Items)
            {
                wakeupSleepConfig.AddWUPSleepInfo(
                    new WUPSleepInfo(
                        Convert.ToByte(listViewItem.SubItems[0].Text),
                        (ConfigState)Enum.Parse(typeof(ConfigStateRequested), listViewItem.SubItems[1].Text),
                        (ConfigState)Enum.Parse(typeof(ConfigStateRequested), listViewItem.SubItems[2].Text),
                        Convert.ToByte(listViewItem.SubItems[3].Text)));
            }

            return wakeupSleepConfig;
        }

        #region Methods

        private void OnAddWUPSleepInfoClicked(object sender, EventArgs e)
        {
            if (this.listViewWUPSleepInfo.Items.Count >= 255)
            {
                MessageBox.Show("Maximum number of wakeup/sleep infos reached.", "Maximum reached", MessageBoxButtons.OK);
                return;
            }

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

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

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

            this.labelNumberOfInfos.Text = this.listViewWUPSleepInfo.Items.Count.ToString(CultureInfo.InvariantCulture);
        }

        #endregion
    }
}