@using Moonlight.App.Services
@using Moonlight.App.Services.Users
@using Moonlight.App.Models.Forms
@using Moonlight.App.Models.Enums
@using Moonlight.App.Models.Forms.Auth

@inject IdentityService IdentityService
@inject UserService UserService

<div class="w-100">
    <div class="card-body">
        <div class="text-start mb-8">
            <h1 class="text-dark mb-3 fs-3x">
                Change your password
            </h1>
            <div class="text-gray-400 fw-semibold fs-6">
                You need to change your password in order to continue
            </div>
        </div>

        <SmartForm Model="Form" OnValidSubmit="OnValidSubmit">
            <div class="fv-row mb-7">
                <input @bind="Form.Password" type="password" placeholder="Password" class="form-control form-control-solid">
            </div>

            <div class="fv-row mb-7">
                <input @bind="Form.RepeatedPassword" type="password" placeholder="Repeat password" class="form-control form-control-solid">
            </div>

            <div class="d-flex flex-stack">
                <button type="submit" class="btn btn-primary me-2 flex-shrink-0">Continue</button>
            </div>
        </SmartForm>
    </div>
</div>

@code
{
    private UpdateAccountPasswordForm Form = new();

    private async Task OnValidSubmit()
    {
        if (Form.Password != Form.RepeatedPassword)
            throw new DisplayException("The password do not match");

    // Because of UserService.Auth.ChangePassword may logout the user before we can reset the flag
    // we reset the flag before changing the password and if any error occurs we simple set it again
        
        try
        {
            IdentityService.Flags[UserFlag.PasswordPending] = false;
            await IdentityService.SaveFlags();
            
            await UserService.Auth.ChangePassword(IdentityService.CurrentUser, Form.Password);
        }
        catch (Exception)
        {
            IdentityService.Flags[UserFlag.PasswordPending] = true;
            await IdentityService.SaveFlags();
            
            throw;
        }
        
        await IdentityService.Authenticate();
    }
}