@layout PageLayout
@implements IDisposable

@inject IToastService toastService

<div style="display:grid; gap: 8px;padding: 16px; height: 94vh; width: 90vw; margin: auto; margin-top: 32px;
grid-template-columns: 27% 25% 25% 23%; grid-template-rows: auto;
grid-template-areas: 'loader sand compare compare' ;">


    <div style="grid-area: loader; border: 2px solid black; padding: 20px;">
        Comparision Loader
        <BuildLoaderComponent></BuildLoaderComponent>
    </div>

    <div style="grid-area: sand; border: 2px solid black; padding: 20px;">
        Sand
        <SandComponent></SandComponent>
    </div>


    <div style="grid-area: compare; border: 2px solid black; padding: 20px;">
        Comparision Charts

    </div>


</div>

@code {

    [Inject]
    IKeyService KeyService { get; set; } = default!;

    [Inject]
    IImmortalSelectionService FilterService { get; set; } = default!;

    [Inject]
    IBuildOrderService BuildOrderService { get; set; } = default!;

    [Inject]
    IEconomyService EconomyService { get; set; } = default!;


    [Inject]
    ITimingService TimingService { get; set; } = default!;


    Dictionary<int, List<EntityModel>> completedEntities = new();


    List<EntityModel> entities = EntityModel.GetListOnlyHotkey();

    protected override void OnInitialized()
    {
        KeyService.Subscribe(HandleClick);
        FilterService.Subscribe(StateHasChanged);
        EconomyService.Subscribe(StateHasChanged);
        TimingService.Subscribe(HandleTimingChanged);
        EconomyService.Calculate(BuildOrderService, TimingService, 0);
    }

    void IDisposable.Dispose()
    {
        KeyService.Unsubscribe(HandleClick);
        FilterService.Unsubscribe(StateHasChanged);
        TimingService.Unsubscribe(StateHasChanged);
        EconomyService.Unsubscribe(StateHasChanged);
    }


    protected void HandleTimingChanged()
    {
        EconomyService.Calculate(BuildOrderService, TimingService, BuildOrderService.GetLastRequestInterval());
    }

    protected void HandleClick()
    {
        var hotkey = KeyService.GetHotkey();
        var hotkeyGroup = KeyService.GetHotkeyGroup();
        var isHoldSpace = KeyService.IsHoldingSpace();
        var faction = FilterService.GetFactionType();
        var immortal = FilterService.GetImmortalType();

        if (hotkey == "`")
        {
            BuildOrderService.RemoveLast();
            EconomyService.Calculate(BuildOrderService, TimingService, BuildOrderService.GetLastRequestInterval());
            StateHasChanged();
            return;
        }

        var entity = EntityModel.GetFrom(hotkey!, hotkeyGroup, isHoldSpace, faction, immortal);
        if (entity == null)
        {
            return;
        }
        if (BuildOrderService.Add(entity, EconomyService))
        {
            EconomyService.Calculate(BuildOrderService, TimingService, BuildOrderService.GetLastRequestInterval());
        }
    }

}