@using Moonlight.Shared.Components.ErrorBoundaries
@using Moonlight.Shared.Components.Auth
@using Moonlight.App.Database.Entities
@using Moonlight.App.Extensions
@using Moonlight.App.Models.Misc
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Moonlight.App.Services.Sessions
@using Moonlight.App.Events

@implements IDisposable
@inherits LayoutComponentBase

@inject IJSRuntime JsRuntime
@inject IdentityService IdentityService
@inject SessionClientService SessionClientService
@inject NavigationManager NavigationManager
@inject EventSystem Event
@inject ToastService ToastService
@inject SmartTranslateService SmartTranslateService
@inject IpBanService IpBanService
@inject DynamicBackgroundService DynamicBackgroundService
@inject KeyListenerService KeyListenerService
@inject ConfigService ConfigService
@inject IpVerificationService IpVerificationService

@{
    var uri = new Uri(NavigationManager.Uri);
    var pathParts = uri.LocalPath.Split("/").Reverse();

    var title = "";

    foreach (var pathPart in pathParts)
    {
        if (!string.IsNullOrEmpty(pathPart))
        {
            if (pathPart == pathParts.Last())
                title += $"{pathPart.FirstCharToUpper()} ";
            else
                title += $"{pathPart.FirstCharToUpper()} - ";
        }
    }
}

<GlobalErrorBoundary>
    <PageTitle>@(string.IsNullOrEmpty(title) ? "Dashboard - " : title)Moonlight</PageTitle>

    <DefaultLayout>
        <SoftErrorBoundary>
            @if (UserProcessed)
            {
                if (IsIpBanned)
                {
                    <div class="modal d-block">
                        <div class="modal-dialog modal-dialog-centered mw-900px">
                            <div class="modal-content">
                                <div class="pt-2 modal-body py-lg-10 px-lg-10">
                                    <h2>@(SmartTranslateService.Translate("Your ip has been banned"))</h2>
                                    <p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Your ip address has been banned by an admin"))</p>
                                </div>
                            </div>
                        </div>
                    </div>
                }
                else if (IsIpSuspicious)
                {
                    <div class="modal d-block">
                        <div class="modal-dialog modal-dialog-centered mw-900px">
                            <div class="modal-content">
                                <div class="pt-2 modal-body py-lg-10 px-lg-10">
                                    <h2>@(SmartTranslateService.Translate("Your ip his blocked. VPNs and Datacenter IPs are prohibited from accessing this site"))</h2>
                                    <p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Please disable your vpn or proxy and try it again"))</p>
                                </div>
                            </div>
                        </div>
                    </div>
                }
                else
                {
                    if (uri.LocalPath != "/login" &&
                        uri.LocalPath != "/passwordreset" &&
                        uri.LocalPath != "/register")
                    {
                        if (IdentityService.User == null)
                        {
                            <Login></Login>
                        }
                        else
                        {
                            if (IdentityService.User.Status == UserStatus.Banned)
                            {
                                <BannedAlert></BannedAlert>
                            }
                            else if (IdentityService.User.Status == UserStatus.Disabled)
                            {
                                <DisabledAlert></DisabledAlert>
                            }
                            else if (IdentityService.User.Status == UserStatus.PasswordPending)
                            {
                                <PasswordChangeView></PasswordChangeView>
                            }
                            else if (IdentityService.User.Status == UserStatus.DataPending)
                            {
                                <UserDataSetView></UserDataSetView>
                            }
                            else
                            {
                                <RenderPermissionChecker>
                                    @Body
                                </RenderPermissionChecker>

                                <RatingPopup/>
                            }
                        }
                    }
                    else
                    {
                        if (uri.LocalPath == "/login")
                        {
                            <Login></Login>
                        }
                        else if (uri.LocalPath == "/register")
                        {
                            <Register></Register>
                        }
                        else if (uri.LocalPath == "/passwordreset")
                        {
                            <PasswordReset></PasswordReset>
                        }
                    }
                }
            }
            else
            {
                <div class="modal d-block">
                    <div class="modal-dialog modal-dialog-centered mw-900px">
                        <div class="modal-content">
                            <div class="pt-2 modal-body py-lg-10 px-lg-10">
                                <h2>@(SmartTranslateService.Translate("Authenticating"))...</h2>
                                <p class="mt-3 fw-normal fs-6">@(SmartTranslateService.Translate("Verifying token, loading user data"))</p>
                            </div>
                        </div>
                    </div>
                </div>
            }
        </SoftErrorBoundary>
    </DefaultLayout>
</GlobalErrorBoundary>

@code
{
    private bool UserProcessed = false;
    private bool IsIpBanned = false;
    private bool IsIpSuspicious = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                DynamicBackgroundService.OnBackgroundImageChanged += async (_, _) => { await InvokeAsync(StateHasChanged); };

                await Event.On<Object>("ipBan.update", this, async _ =>
                {
                    IsIpBanned = await IpBanService.IsBanned();
                    NavigationManager.NavigateTo(NavigationManager.Uri, true);
                });

                await IdentityService.Load();

                IsIpBanned = await IpBanService.IsBanned();
                IsIpSuspicious = await IpVerificationService.IsDatacenterOrVpn(IdentityService.Ip);

                UserProcessed = true;
                await InvokeAsync(StateHasChanged);

                await SessionClientService.Start();

                NavigationManager.LocationChanged += async (_, _) =>
                {
                    if (!NavigationManager.Uri.Contains("/server/"))
                        await DynamicBackgroundService.Reset();
                };

                if (IdentityService.User != null)
                {
                    await Event.On<SupportChatMessage>(
                        $"supportChat.{IdentityService.User.Id}.message",
                        this,
                        async message =>
                        {
                            if (!NavigationManager.Uri.EndsWith("/support") && message.Sender != IdentityService.User)
                            {
                                await ToastService.Info($"Support: {message.Content}");
                            }
                        });
                }

                await KeyListenerService.Initialize();

                if (ConfigService.Get().Moonlight.EnableLatencyCheck)
                {
                    await JsRuntime.InvokeVoidAsync("moonlight.loading.checkConnection",
                        ConfigService.Get().Moonlight.AppUrl,
                        ConfigService.Get().Moonlight.LatencyCheckThreshold);
                }
            }
            catch (Exception)
            {
    // ignored
            }
        }
    }

    public async void Dispose()
    {
        await SessionClientService.Stop();

        await KeyListenerService.DisposeAsync();

        if (IdentityService.User != null)
        {
            await Event.Off($"supportChat.{IdentityService.User.Id}.message", this);
        }
    }
}