using System.Collections.Generic;
using InABox.Core;
using InABox.DynamicGrid;

namespace InABox.Wpf;

public abstract class MasterDetailGridPage<TMaster, TGrid, TDetail> : MasterDetailPage<TMaster> 
    where TGrid : DynamicGrid<TDetail>, IDataModelSource, IMasterDetailControl<TMaster,TDetail>, new()
    where TDetail : BaseObject, new()
{

    public TGrid? Grid { get; set; }

    public MasterDetailGridPage(DynamicTabItem tab) : base(tab)
    {
        
    }

    public override Dictionary<string, object[]>? Selected()
    {
        return Grid is not null
            ? new Dictionary<string, object[]>
            {
                { typeof(TDetail).EntityName(), Grid.SelectedRows }
            }
            : null;
    }

    protected abstract void DoRefresh(TGrid grid, bool columns);

    public override IDataModelSource DataModelSource() => CheckGrid();

    private IDataModelSource CheckGrid()
    {
        if (Grid == null)
        {
            Grid = new TGrid();
            Tab.Content = Grid;
        }
        return Grid;
    }
    
    protected override IDataModelSource Refresh()
    {
        bool bFirst = Grid == null;
        CheckGrid();
        Grid.Master = Master;
        DoRefresh(Grid,bFirst);

        return Grid;
    }
}