using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using InABox.Core;

namespace InABox.DynamicGrid;

public class TextBoxEditorControl : DynamicEditorControl<string, TextBoxEditor>
{
    
    static TextBoxEditorControl()
    {
        //DynamicEditorControlFactory.Register<TextBoxEditorControl, TextBoxEditor>();
    }
    
    private TextBox Editor;

    private bool IsChanged;

    public override void Configure()
    {
    }

    protected override FrameworkElement CreateEditor()
    {
        var dock = new DockPanel();

        var buttons = CreateButtons(out var DisableEditor);
        foreach (var button in buttons)
        {
            button.SetValue(DockPanel.DockProperty, Dock.Right);
            dock.Children.Add(button);
        }

        Editor = new TextBox
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch
        };
        Editor.SetValue(DockPanel.DockProperty, Dock.Left);
        if (DisableEditor)
        {
            Editor.Background = new SolidColorBrush(Colors.Silver);
            Editor.IsEnabled = false;
        }

        
        Editor.TextChanged += (o, e) =>
        {
            if (Loaded)
            {
                IsChanged = true;
                if (EditorDefinition.ImmediateUpdates)
                    CheckChanged();
            }
        };


        Editor.LostFocus += (o, e) =>
        {
            if (IsChanged)
                CheckChanged();
        };
        dock.Children.Add(Editor);
        return dock;
    }

    public override int DesiredHeight()
    {
        return 25;
    }

    public override int DesiredWidth()
    {
        return int.MaxValue;
    }

    protected override string RetrieveValue()
    {
        return Editor.Text;
    }

    protected override void UpdateValue(string value)
    {
        if (Editor != null && value != Editor.Text)
        {
            Editor.Text = value;
            if (Loaded)
                CheckChanged();
        }
    }

    public override void SetFocus()
    {
        Editor.Focus();
        Editor.CaretIndex = string.IsNullOrEmpty(Value) ? 0 : Value.Length;
    }

    public override void SetColor(Color color)
    {
        Editor.Background = new SolidColorBrush(color);
    }
}