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

namespace InABox.DynamicGrid;

public abstract class DynamicGridComboBoxColumn<TEditor> : DynamicGridEditorColumn<TEditor, GridComboBoxColumn, TreeGridComboBoxColumn>
    where TEditor : class, ILookupEditor 
{
    private List<Tuple<object?, string>> GetData(TEditor editor)
    {
        var keycol = Definition.ColumnName.Split('.').Last();
        var data = editor.Values(Definition.ColumnName, null);

        var items = new List<Tuple<object?, string>>
        {
            new(null, "")
        };
        foreach (var row in data.Rows)
            items.Add(new(row[keycol], (row["Display"] ?? "").ToString() ?? ""));
        return items;
    }

    protected override void Configure(GridComboBoxColumn column, TEditor editor)
    {
        column.SelectedValuePath = "Item1";
        column.DisplayMemberPath = "Item2";
        column.ItemsSource = GetData(editor);
        column.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
    }

    protected override void Configure(TreeGridComboBoxColumn column, TEditor editor)
    {
        column.SelectedValuePath = "Item1";
        column.DisplayMemberPath = "Item2";
        column.ItemsSource = GetData(editor);
        column.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
    }

    protected DynamicGridComboBoxColumn(DynamicGridColumn definition) : base(definition)
    {
    }
}