@using Moonlight.App.Services
@using Moonlight.App.Models.Abstractions
@using Moonlight.App.Models.Enums
@using Moonlight.Shared.Components.Auth

@inherits LayoutComponentBase
@implements IDisposable

@inject CookieService CookieService
@inject ConfigService ConfigService
@inject IdentityService IdentityService
@inject SessionService SessionService
@inject NavigationManager Navigation

@{
    var url = new Uri(Navigation.Uri);
}

@if (Initialized)
{
    if (IdentityService.IsSignedIn)
    {
        if (!IdentityService.Flags[UserFlag.MailVerified] && ConfigService.Get().Security.EnableEmailVerify)
        {
            <OverlayLayout>
                <MailVerify />
            </OverlayLayout>
        }
        else if (IdentityService.Flags[UserFlag.PasswordPending])
        {
            <OverlayLayout>
                <ChangePassword />
            </OverlayLayout>
        }
        else
        {
            <DefaultLayout>
                <SoftErrorHandler>
                    <PermissionChecker>
                        @Body
                    </PermissionChecker>
                </SoftErrorHandler>
            </DefaultLayout>
        }
    }
    else
    {
        if (url.LocalPath == "/register")
        {
            <OverlayLayout>
                <Register />
            </OverlayLayout>
        }
        else if (url.LocalPath == "/password-reset")
        {
            <OverlayLayout>
                <PasswordReset />
            </OverlayLayout>
        }
        else
        {
            <OverlayLayout>
                <Login />
            </OverlayLayout>
        }
    }
}
else
{
    <OverlayLayout>
        <div class="w-100">
            <div class="card-body">
                <div class="text-center mb-10">
                    <h1 class="text-dark mb-3 fs-4">
                        Connecting to the remote server
                    </h1>
                    <div class="text-gray-400 fw-semibold fs-6">
                        <div class="text-success">
                            <div class="spinner-border me-2" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </OverlayLayout>
}

@code
{
    private bool Initialized = false;

    private Session? MySession;

    protected override void OnInitialized()
    {
        IdentityService.OnAuthenticationStateChanged += async (_, _) =>
        {
            if (MySession != null)
            {
                MySession.User = IdentityService.CurrentUserNullable;
                MySession.UpdatedAt = DateTime.UtcNow;
            }

            await InvokeAsync(StateHasChanged);
        };

        Navigation.LocationChanged += (_, _) =>
        {
            if (MySession != null)
            {
                MySession.Url = Navigation.Uri;
                MySession.UpdatedAt = DateTime.UtcNow;
            }
        };
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            var token = await CookieService.GetValue("token");
            await IdentityService.Authenticate(token);

            MySession = new()
            {
    //Ip = ConnectionService.GetIp(), TODO: Implement
                Url = Navigation.Uri,
                User = IdentityService.CurrentUserNullable
            };

            await SessionService.Register(MySession);

            Initialized = true;

            await InvokeAsync(StateHasChanged);
        }
    }

    public async void Dispose() // This method will be called if the user closes his tab
    {
        if (MySession != null)
            await SessionService.Unregister(MySession);
    }
}