using InABox.Wpf;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace InABox.WPF
{
    /// <summary>
    ///     Interaction logic for PrinterSelection.xaml
    /// </summary>
    public partial class DictionaryComboEdit : ThemableWindow
    {

        public string Description
        {
            get => Label.Content as string ?? "Select Value";
            set => Label.Content = value;
        }
        
        public DictionaryComboEdit(string[] values, ref int index)
        {
            InitializeComponent();
            Combo.Items.Clear();
            Combo.Items.Add("");
            foreach (var val in values)
                Combo.Items.Add(val);
            Index = index;
        }

        public int Index
        {
            get => Combo.SelectedIndex - 1;
            set => Combo.SelectedIndex = value + 1;
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        public static bool Execute<T>(Dictionary<T, string> values, ref T value, string? title = null, string? description = null) where T : notnull
        {
            var index = values.Keys.ToList().IndexOf(value);
            var edit = new DictionaryComboEdit(values.Values.ToArray(), ref index);
            edit.Title = title ?? "Value Selection";
            edit.Description = description ?? "Select Value";
            if (edit.ShowDialog() == true)
            {
                value = edit.Index > -1 ? values.Keys.ToList()[edit.Index] : default;
                return true;
            }

            return false;
        }

        private void Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            OK.IsEnabled = Combo.SelectedIndex > 0;
        }
    }
}