using System;
using System.Collections.Generic;
using InABox.Core;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.TreeGrid;

namespace InABox.DynamicGrid;

/// <remarks>
/// Unless <see cref="IDynamicGridEditorColumn{TEntity}"/> is used, the editor type <b>must</b> be non-generic.
/// </remarks>
public interface IDynamicGridEditorColumn : IDynamicColumnBase
{
    DynamicGridColumn Definition { get; set; }
    string MappingName { get; }
    string TreeMappingName { get; }
    List<string> ExtraColumns { get; }

    bool VariableWidth { get; }
    bool VariableHeight { get; }
    bool Filtered { get; }
    bool Editable { get; }

    IDynamicGridSummary? Summary();

    GridColumn CreateGridColumn();
    TreeGridColumn CreateTreeGridColumn();

    void UpdateUIComponent(IDynamicGridGridUIComponent component);
}

/// <summary>
/// Indicates that this editor only makes sense in a context with a parent entity. If this interface is used, the editor <b>must</b> have
/// a single generic type argument, which is <typeparamref name="TEntity"/>.
/// </summary>
public interface IDynamicGridEditorColumn<TEntity> : IDynamicGridEditorColumn
{
    Func<BaseObject?>? GetEntity { get; set; }

    event DynamicColumnEntityChangedEvent? EntityChanged;

    void DoEntityChanged(String columnname, Dictionary<string, object?> changes);
}

public static class DynamicGridEditorColumnExtensions
{
    public static void UpdateData<T>(this IDynamicGridEditorColumn<T> column, Dictionary<string, object?> updates)
    {
        var entity = column.GetEntity?.Invoke();
        if (entity != null)
        {
            var changes = new Dictionary<string, object?>();
            foreach (var key in updates.Keys)
                DynamicGridUtils.UpdateEditorValue(new BaseObject[] { entity }, key, updates[key], changes);
            column.DoEntityChanged(column.Definition.ColumnName, changes);
        }
    }
}
