using InABox.Core;
using InABox.WPF;
using Syncfusion.Windows.Shared;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace InABox.DynamicGrid
{
    public class DFStringControl : DynamicFormFieldControl<DFLayoutStringField, DFLayoutStringFieldProperties, string, string?>
    {
        private string? text;

        private TextBox? TextBox;
        private Button? Btn;

        [NotNull]
        private string? Text
        {
            get => (Field.Properties.PopupEditor ? text : TextBox?.Text) ?? "";
            set
            {
                if (Field.Properties.PopupEditor)
                {
                    text = value;
                }
                else if(TextBox is not null)
                {
                    TextBox.Text = value;
                }
            }
        }

        public override void SetSerializedValue(string? value)
        {
            Text = value;
        }

        public override string? GetSerializedValue()
        {
            return Text;
        }

        protected override FrameworkElement Create()
        {
            FrameworkElement element;
            if (Field.Properties.PopupEditor)
            {
                Btn = new Button { Content = "..." };
                Btn.Click += Btn_Click;
                element = Btn;
            }
            else
            {
                TextBox = new TextBox();
                TextBox.Text = Field.Properties.Default;
                TextBox.TextWrapping = Field.Properties.TextWrapping ? TextWrapping.Wrap : TextWrapping.NoWrap;
                TextBox.VerticalContentAlignment = VerticalAlignment.Top;
                TextBox.TextAlignment = TextAlignment.Left;
                TextBox.TextChanged += (sender, e) => ChangeField();
                element = TextBox;
            }

            return element;
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            var text = Text;
            if(TextBoxDialog.Execute("Edit Comment", ref text))
            {
                Text = text;
            }
        }

        public override string GetValue() => Text;

        public override void SetValue(string? value) => Text = value;

        protected override bool IsEmpty() => string.IsNullOrWhiteSpace(Text);
    }
}
