
@inherits BasePage

@page "/database/{text}"

@inject IEntityDisplayService EntityDisplayService
@using Model
@implements IDisposable


<LayoutLargeContentComponent>

    <PaperComponent>
        <FormDisplayComponent Label="Patch">
            <Display>
                Game Patch: @Variables.GamePatch
            </Display>
        </FormDisplayComponent>
    </PaperComponent>

    <div style="margin-left: 8px">
        <ButtonGroupComponent OnClick="choice => { EntityDisplayService.SetDisplayType(choice); }"
                              Choice="@EntityDisplayService.GetDisplayType()"
                              Choices="@EntityDisplayService.DefaultChoices()"></ButtonGroupComponent>
    </div>


    @if (Text!.Trim().ToLower().Equals("walter"))
    {
        <PaperComponent>
            <CodeComponent>
                Unhandled Exception: EXCEPTION_MEMORY_SIZE_VIOLATION
                UNIT_WALTER too powerful to be displayed.

                This SHOULD NEVER HAPPEN!
            </CodeComponent>
        </PaperComponent>
    }
    else if (_entity == null)
    {
        <PaperComponent>
            <div>Invalid entity name entered: <span id="invalidSearch">@Text</span></div>
            <div>No such entity. Did you mean <b>"<span id="validSearch">Throne</span>"</b>?</div>
        </PaperComponent>
    }

    else
    {
        <PaperComponent>
            <CascadingValue Value="_entity">
                <CascadingValue Value="@EntityDisplayService.GetDisplayType()">

                    <EntityViewComponent></EntityViewComponent>
                </CascadingValue>
            </CascadingValue>

        </PaperComponent>
    }

</LayoutLargeContentComponent>


@code {

    [Parameter] public string? Text { get; set; }

    private EntityModel? _entity;

    protected override void OnInitialized()
    {
        EntityDisplayService.Subscribe(StateHasChanged);
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        base.OnInitialized();

        FocusEntity();
    }

    private void FocusEntity()
    {
        foreach (var e in EntityData.Get().Values)
        {
            if (e.Info().Name.ToLower().Equals(Text!.ToLower()))
            {
                _entity = e;
                return;
            }
        }
    }

    void IDisposable.Dispose()
    {
        EntityDisplayService.Unsubscribe(StateHasChanged);
    }

}