@page "/Profile/ChangePassword"
@using Microsoft.AspNetCore.Components.Authorization;
@layout ProfileLayout
@inject UserManager<User> UserManager
@inject IMessageService MessageService
@inject AuthenticationStateProvider AuthenticationStateProvider
@attribute [Authorize]

<PageHeader Title="Change Password" />

<div style="padding: 0 24px;">
    <Form Model="Model" Layout="@FormLayout.Vertical">
        <FormItem Label="Current Password">
            <InputPassword @bind-Value="context.CurrentPassword" />
        </FormItem>
        <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 {
    User User;
    ChangePasswordModel Model = new ChangePasswordModel();

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        if (authState.User.Identity.IsAuthenticated)
            User = await UserManager.FindByNameAsync(authState.User.Identity.Name);
    }

    async void Change()
    {
        try
        {
            if (Model.NewPassword == Model.NewPasswordConfirm)
            {
                var result = await UserManager.ChangePasswordAsync(User, Model.CurrentPassword, Model.NewPassword);

                if (result.Succeeded)
                    await MessageService.Success("Password changed!");
                else
                    foreach (var error in result.Errors)
                        await MessageService.Error(error.Description);
            }
            else
                await MessageService.Error("Passwords don't match!");
        }
        catch (Exception ex)
        {
            await MessageService.Error("Password could not be changed!");
        }
    }

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