@page "/Settings/Users/{id:guid}/ChangePassword"
@layout SettingsLayout
@inject UserManager<User> UserManager
@inject IMessageService MessageService
@attribute [Authorize(Roles = "Administrator")]

<PageHeader Title="Change Password" Subtitle="@User.UserName" />

<div style="padding: 0 24px;">
    <Form Model="Model" Layout="@FormLayout.Vertical">
        <FormItem Label="New Password">
            <InputPassword @bind-Value="context.NewPassword" />
        </FormItem>

        <FormItem Label="Confirm Password">
            <InputPassword @bind-Value="context.NewPasswordConfirm" />
        </FormItem>

        <FormItem>
            <Button OnClick="Change" Type="@ButtonType.Primary">Change</Button>
        </FormItem>
    </Form>
</div>

@code {
    [Parameter] public Guid Id { get; set; }

    User User;
    ChangePasswordModel Model = new ChangePasswordModel();

    protected override async Task OnInitializedAsync()
    {
        if (Id != Guid.Empty)
        {
            User = await UserManager.FindByIdAsync(Id.ToString());
        }
    }

    async void Change()
    {
        try
        {
            var token = await UserManager.GeneratePasswordResetTokenAsync(User);

            if (Model.NewPassword == Model.NewPasswordConfirm)
                await UserManager.ResetPasswordAsync(User, token, Model.NewPassword);

            await MessageService.Success("Password changed!");
        }
        catch
        {
            await MessageService.Error("The user's password could not be changed");
        }
    }

    public class ChangePasswordModel
    {
        public string NewPassword { get; set; }
        public string NewPasswordConfirm { get; set; }
    }
}
