using InABox.Wpf;
using System.Windows;

namespace InABox.WPF
{
    /// <summary>
    ///     Interaction logic for NumberEdit.xaml
    /// </summary>
    public partial class DoubleEdit : ThemableWindow
    {
        public DoubleEdit(string title, double min, double max, double value)
        {
            InitializeComponent();
            Title = title;
            Value = value;
            Editor.MinValue = min;
            Editor.MaxValue = max;
        }

        public double Value
        {
            get => Editor.Value.HasValue ? Editor.Value.Value : 0;
            set => Editor.Value = value;
        }

        private void Confirm()
        {
            if (Editor.Value >= Editor.MinValue && Editor.Value <= Editor.MaxValue)
            {
                DialogResult = true;
                Close();
            }
            else
            {
                MessageBox.Show($"Value must be in range [{Editor.MinValue}, {Editor.MaxValue}]");
            }
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            Confirm();
        }

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

        public static bool Execute(string title, double min, double max, ref double value)
        {
            var edit = new DoubleEdit(title, min, max, value);
            if (edit.ShowDialog() == true)
            {
                value = edit.Value;
                return true;
            }

            return false;
        }

        private void ThemableWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Editor.Focus();
        }

        private void Editor_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if(e.Key == System.Windows.Input.Key.Enter)
            {
                Confirm();
            }
        }
    }
}