using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json;
using System.Windows.Forms;

namespace CareFusion.ITSystemSimulator
{
    public partial class FormMasterArticleProductCodes : Form
    {
        public FormMasterArticleProductCodes(string serializedProductCodes)
        {
            InitializeComponent();
            this.LoadProductCodesFromList(string.IsNullOrEmpty(serializedProductCodes)
                ? new List<string>()
                : JsonSerializer.Deserialize<List<string>>(serializedProductCodes));
        }

        public string GetSerializedProductCodes()
            => JsonSerializer.Serialize(SaveProductCodesToList());

        #region Private methods

        private void LoadProductCodesFromList(List<string> productCodes)
        {
            Debug.Assert(productCodes != null);

            this.lstProductCodes.Items.Clear();

            productCodes.ForEach(item => lstProductCodes.Items.Add(item));
        }

        public List<string> SaveProductCodesToList()
        {
            var response = new List<string>();

            foreach (var item in this.lstProductCodes.Items)
            {
                response.Add(item.ToString());
            }

            return response;
        }

        private void txtboxProductCode_KeyUp(object sender, KeyEventArgs e)
        {
            this.btnAddProductCode.Enabled = !string.IsNullOrEmpty(((TextBox)sender).Text);
        }

        private void btnAddProductCode_Click(object sender, System.EventArgs e)
        {
            this.lstProductCodes.Items.Add(this.txtboxProductCode.Text);
            this.txtboxProductCode.Text = default;
            this.txtboxProductCode.Focus();
            this.btnAddProductCode.Enabled = false;
        }

        private void lstProductCodes_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            var selectedItemText = this.lstProductCodes.SelectedItem?.ToString();

            this.btnEditProductCode.Enabled = !string.IsNullOrEmpty(selectedItemText);
            this.btnRemoveProductCode.Enabled = !string.IsNullOrEmpty(selectedItemText);
        }

        private void btnEditProductCode_Click(object sender, System.EventArgs e)
        {
            var selectedItem = this.lstProductCodes.SelectedItem;
            this.txtboxProductCode.Text = selectedItem.ToString();
            this.lstProductCodes.Items.Remove(selectedItem);
            this.btnAddProductCode.Enabled = true;
        }

        private void btnRemoveProductCode_Click(object sender, System.EventArgs e)
        {
            this.lstProductCodes.Items.Remove(this.lstProductCodes.SelectedItem);
        }

        #endregion
    }
}
