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

namespace InABox.Wpf;

public interface IMasterDetailPanelPage
{
    IBasePanel? Panel { get; }
}

public abstract class MasterDetailPanelPage<TMaster,TPanel> : MasterDetailPage<TMaster>, IMasterDetailPanelPage
    where TPanel : class, IBasePanel, IMasterDetailControl<TMaster>, new()
{
    protected MasterDetailPanelPage(DynamicTabItem tab) : base(tab) { }
    
    public TPanel? Panel { get; set; }

    IBasePanel? IMasterDetailPanelPage.Panel => Panel;
    
    public override Dictionary<string, object[]>? Selected() => Panel?.Selected();

    protected abstract void DoRefresh(TPanel? panel);

    public override IDataModelSource? DataModelSource() => CheckPanel();
    
    protected override IDataModelSource? Refresh()
    {
        CheckPanel();
        DoRefresh(Panel);

        return Panel;
    }

    public override void CreateToolbarButtons(IPanelHost host)
    {
        CheckPanel().CreateToolbarButtons(host);
    }

    public override void Heartbeat(TimeSpan time)
    {
        Panel?.Heartbeat(time);
    }

    public override void Shutdown(CancelEventArgs? cancel)
    {
        Panel?.Shutdown(cancel);
    }

    private TPanel CheckPanel()
    {
        if (Panel == null)
        {
            Panel = PanelUtils.LoadPanel<TPanel>();
            Panel.OnUpdateDataModel += UpdateDataModel;
            Tab.Content = Panel;
        }

        Panel.Master = Master;
        return Panel;
    }
}