using System.Windows;

namespace InABox.Wpf.Editors
{
    public partial class TextEdit : ThemableWindow
    {
        public TextEdit()
        {
            InitializeComponent();
        }

        public TextEdit(string caption, string text = "")
        {
            InitializeComponent();

            Title = caption;
            TextEditor.Text = text;
        }

        public TextEdit(string caption, string prompt, string text = "")
        {
            InitializeComponent();

            Title = caption;
            Prompt.Content = prompt;
            TextEditor.Text = text;
        }
        
        public string Text
        {
            get => TextEditor.Text;
            set => TextEditor.Text = value;
        }

        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(string caption, ref string text)
        {
            var editor = new TextEdit(caption, text);
            if (editor.ShowDialog() == true)
            {
                text = editor.Text;
                return true;
            }

            return false;
        }
        
        public static bool Execute(string caption, string prompt, ref string text)
        {
            var editor = new TextEdit(caption, prompt, text);
            if (editor.ShowDialog() == true)
            {
                text = editor.Text;
                return true;
            }

            return false;
        }

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

        private void TextEditor_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            switch (e.Key)
            {
                case System.Windows.Input.Key.Enter:
                    DialogResult = true;
                    Close();
                    break;
                case System.Windows.Input.Key.Escape:
                    DialogResult = false;
                    Close();
                    break;
            }
        }
    }
}