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;

namespace InABox.DynamicGrid;

public class DynamicGridCodeColumn<TEntity> : DynamicGridEditorColumn<TEntity,CodeEditor,GridTemplateColumn> where TEntity : BaseObject
{

    protected override void Configure(GridTemplateColumn column, CodeEditor editor)
    {
        column.CellTemplate = TemplateGenerator.CreateDataTemplate
        (
            () =>
            {
                var result = new Label();
                result.HorizontalContentAlignment = Column.TextAlignment == TextAlignment.Left
                    ? HorizontalAlignment.Left
                    : Column.TextAlignment == TextAlignment.Center
                        ? HorizontalAlignment.Center
                        : HorizontalAlignment.Right;
                var binding = new Binding()
                {
                    Path = new PropertyPath(MappingName),
                };
                result.SetBinding(Label.ContentProperty, binding);
                return result;
            }
        );

        column.EditTemplate = TemplateGenerator.CreateDataTemplate
        (
            () =>
            {
                var textbox = new TextBox();
                textbox.CharacterCasing = CharacterCasing.Upper;
                textbox.TextAlignment = Column.TextAlignment;
                textbox.SetBinding(TextBox.TextProperty, new Binding()
                {
                    Path = new PropertyPath(MappingName)
                });
                
                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)
    {
    }
}