using InABox.Core;
using InABox.WPF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace InABox.DynamicGrid;

public class DynamicColumnNameEditorControl : DynamicEditorControl<string, DynamicColumnNameEditor>
{
    private TextBox TextBox = null!;
    private Button Edit = null!;

    private string _value = "";

    public override void Configure()
    {
    }

    protected override FrameworkElement CreateEditor()
    {
        var grid = new Grid
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            HorizontalAlignment = HorizontalAlignment.Stretch
        };
        grid.AddColumn(GridUnitType.Star);
        grid.AddColumn(GridUnitType.Auto);

        TextBox = new TextBox
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(0, 0, 0, 0),
            IsEnabled = false
        };

        Edit = new Button
        {
            VerticalAlignment = VerticalAlignment.Stretch,
            VerticalContentAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(5, 1, 0, 1),
            Padding = new Thickness(5, 0, 5, 0),
            Width = 20,
            Content = "..",
            Focusable = false,
        };
        Edit.Click += EditButton_Click;

        grid.AddChild(TextBox, 0, 0);
        grid.AddChild(Edit, 0, 1);


        return grid;
    }

    private void EditButton_Click(object sender, RoutedEventArgs e)
    {
        if(EditorDefinition.Schema is not null && DynamicGridColumnNameSelectorGrid.SelectColumnName(EditorDefinition.Schema, out var value))
        {
            _value = value;
            TextBox.Text = _value;
            CheckChanged();
        }
    }

    public override int DesiredHeight()
    {
        return 25;
    }

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

    public override void SetColor(Color color)
    {
        TextBox.Background = color.ToBrush();
    }

    public override void SetFocus()
    {
        TextBox.Focus();
    }

    protected override string RetrieveValue()
    {
        return _value;
    }

    protected override void UpdateValue(string value)
    {
        _value = value;
        TextBox.Text = value;
    }
}
