@using SteUp.Shared.Components.Pages.Utility
@using SteUp.Shared.Components.SingleElements.Modal.ExceptionModal
@using SteUp.Shared.Core.BarcodeReader.Contracts
@inject NavigationManager NavigationManager
@inject IBarcodeManager BarcodeManager

<ErrorBoundary @ref="ErrorBoundary">
    <ChildContent>
        <CascadingAuthenticationState>
            <Router AppAssembly="@typeof(Routes).Assembly" NotFoundPage="typeof(Pages.NotFound)">
                <Found Context="routeData">
                    @if (!LoadData)
                    {
                        <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(Layout.MainLayout)">
                            <Authorizing>
                                <AuthorizingPage/>
                            </Authorizing>
                            <NotAuthorized>
                                @if (context.User.Identity?.IsAuthenticated != true)
                                {
                                    NavigationManager.NavigateTo("/login");
                                }
                                else
                                {
                                    <p role="alert">You are not authorized to access this resource.</p>
                                }
                            </NotAuthorized>
                        </AuthorizeRouteView>
                    }
                    else
                    {
                        <AuthorizingPage/>
                    }

                    <FocusOnNavigate RouteData="@routeData" Selector="h1"/>
                </Found>
            </Router>
        </CascadingAuthenticationState>
    </ChildContent>

    <ErrorContent>
        <ExceptionModal @ref="ExceptionModal"
                        Exception="@context"
                        ErrorBoundary="@ErrorBoundary"
                        OnRetry="() => ErrorBoundary?.Recover()"/>
    </ErrorContent>
</ErrorBoundary>

@code {
    private bool LoadData { get; set; }

    private ErrorBoundary? ErrorBoundary { get; set; }
    private ExceptionModal ExceptionModal { get; set; } = null!;

    protected override async Task OnInitializedAsync()
    {
        LoadData = true;
        StateHasChanged();
        
        await SteupDataService.Init();
        BarcodeManager.Init();
        
        LoadData = false;
        StateHasChanged();
    }

}