using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using InABox.Core;
using InABox.WPF;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.TreeGrid;

namespace InABox.DynamicGrid;

public class DynamicGridCodeColumn : DynamicGridEditorColumn<CodeEditor, GridTemplateColumn, TreeGridTemplateColumn>
{
    protected override void Configure(GridTemplateColumn column, CodeEditor editor)
    {
        column.CellTemplate = CreateCellTemplate(editor, MappingName);
        column.EditTemplate = CreateEditTemplate(editor, column, MappingName);
    }

    protected override void Configure(TreeGridTemplateColumn column, CodeEditor editor)
    {
        column.CellTemplate = CreateCellTemplate(editor, TreeMappingName);
        column.EditTemplate = CreateEditTemplate(editor, column, TreeMappingName);
    }

    private DataTemplate CreateCellTemplate(CodeEditor editor, string mapping)
    {
        return TemplateGenerator.CreateDataTemplate
        (
            () =>
            {
                var result = new Label();
                result.HorizontalContentAlignment = GetHorizontalAlignment(editor);
                result.VerticalContentAlignment = GetVerticalAlignment(editor);
                var binding = new Binding()
                {
                    Path = new PropertyPath(mapping),
                };
                result.SetBinding(Label.ContentProperty, binding);
                return result;
            }
        );
    }

    private DataTemplate CreateEditTemplate(CodeEditor editor, GridColumnBase column, string mapping)
    {
        return TemplateGenerator.CreateDataTemplate
        (
            () =>
            {
                var textbox = new TextBox();
                textbox.CharacterCasing = CharacterCasing.Upper;
                textbox.TextAlignment = column.TextAlignment;
                textbox.SetBinding(TextBox.TextProperty, new Binding()
                {
                    Path = new PropertyPath(mapping)
                });
                
                textbox.SetValue(Grid.ColumnSpanProperty, 2);
                textbox.Padding = new Thickness(2, 0, 0, 0);
                textbox.VerticalContentAlignment = VerticalAlignment.Center;
                textbox.PreviewTextInput += (sender, args) => textbox.Tag = true;
                textbox.TextChanged += (sender, args) =>
                {
                    if (Equals(textbox.Tag, false))
                    {
                        textbox.SelectAll();
                        textbox.Tag = true;
                    }
                };
                textbox.SetValue(FocusManagerHelper.FocusedElementProperty, true);
                
                return textbox;
            }
        );
    }

    public DynamicGridCodeColumn(DynamicGridColumn definition) : base(definition)
    {
    }
}