@inject IJSRuntime JsRuntime
@inject IKeyService KeyService
@inject IImmortalSelectionService FilterService
@inject IStorageService StorageService
@inject IBuildOrderService BuildOrderService
@using Services.Website
@implements IDisposable

@if (_entity != null)
{
    <div class="entityClickView">
        <CascadingValue Value="_entity">
            <CascadingValue Value="@_viewType">
                <EntityViewComponent></EntityViewComponent>
            </CascadingValue>
        </CascadingValue>
    </div>
}
<style>
    .entityClickView {
        overflow-y: scroll;
        width: 100%;
        overflow-x: hidden;
        height: 550px;
    }
</style>

@code {
    private EntityModel? _entity;
    private string _viewType = EntityViewType.Detailed;

    protected override void OnInitialized()
    {
        base.OnInitialized();
        KeyService.Subscribe(HandleClick);
        StorageService.Subscribe(RefreshDefaults);
        BuildOrderService.Subscribe(OnBuildOrderServiceChanged);

        RefreshDefaults();
    }

    void IDisposable.Dispose()
    {
        KeyService.Unsubscribe(HandleClick);
        StorageService.Unsubscribe(RefreshDefaults);
        BuildOrderService.Unsubscribe(OnBuildOrderServiceChanged);
    }


    void OnBuildOrderServiceChanged()
    {
        if (BuildOrderService.GetLastRequestInterval() == 0)
        {
            _entity = null;
            StateHasChanged();
        }
    }

    void RefreshDefaults()
    {
        _viewType = StorageService.GetValue<bool>(StorageKeys.IsPlainView) ? EntityViewType.Plain : EntityViewType.Detailed;
    }

    private void HandleClick()
    {
        var hotkey = KeyService.GetHotkey();
        var hotkeyGroup = KeyService.GetHotkeyGroup();
        var isHoldSpace = KeyService.IsHoldingSpace();
        var faction = FilterService.GetFaction();
        var immortal = FilterService.GetImmortal();

        var foundEntity = EntityModel.GetFrom(hotkey!, hotkeyGroup, isHoldSpace, faction, immortal);

        if (foundEntity != null && _entity != foundEntity)
        {
            _entity = foundEntity;
            StateHasChanged();
        }
    }

}