@namespace Oqtane.Modules.Admin.Reset
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IUserService UserService
@inject IStringLocalizer<Index> Localizer
@inject IStringLocalizer<SharedResources> SharedLocalizer

<form @ref="form" class="@(validated ? "was-validated" : "needs-validation")" novalidate>
    <ModuleMessage Message="@_passwordrequirements" Type="MessageType.Info" />
    <div class="container">
        <div class="row mb-1 align-items-center">
            <Label Class="col-sm-3" For="username" HelpText="Your username will be populated from the link you received in the password reset notification" ResourceKey="Username">Username: </Label>
            <div class="col-sm-9">
                <input id="username" type="text" class="form-control" @bind="@_username" readonly />
            </div>
        </div>
        <div class="row mb-1 align-items-center">
            <Label Class="col-sm-3" For="password" HelpText="The new password. It must satisfy complexity rules for the site." ResourceKey="Password">Password: </Label>
            <div class="col-sm-9">
				<div class="input-group">
					<input id="password" type="@_passwordtype" class="form-control" @bind="@_password" autocomplete="new-password" required />
                    <button type="button" class="btn btn-secondary" @onclick="@TogglePassword" tabindex="-1">@_togglepassword</button>
				</div>
            </div>
        </div>
        <div class="row mb-1 align-items-center">
            <Label Class="col-sm-3" For="confirm" HelpText="Enter the password again. It must exactly match the password entered above." ResourceKey="Confirm">Confirm: </Label>
            <div class="col-sm-9">
				<div class="input-group">
					<input id="confirm" type="@_passwordtype" class="form-control" @bind="@_confirm" autocomplete="new-password" required />
                    <button type="button" class="btn btn-secondary" @onclick="@TogglePassword" tabindex="-1">@_togglepassword</button>
				</div>
            </div>
        </div>
    </div>
    <br />
    <button type="button" class="btn btn-primary" @onclick="Reset">@Localizer["Password.Reset"]</button>
    <button type="button" class="btn btn-secondary" @onclick="Cancel">@SharedLocalizer["Cancel"]</button>
</form>

@code {
	private ElementReference form;
	private bool validated = false;
	private string _username = string.Empty;
	private string _password = string.Empty;
	private string _passwordtype = "password";
	private string _togglepassword = string.Empty;
	private string _confirm = string.Empty;
    private string _passwordrequirements;

	public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Anonymous;

	protected override async Task OnInitializedAsync()
	{
		_togglepassword = SharedLocalizer["ShowPassword"];
        _passwordrequirements = await UserService.GetPasswordRequirementsAsync(PageState.Site.SiteId);

		if (PageState.QueryString.ContainsKey("name") && PageState.QueryString.ContainsKey("token"))
        {
            _username = PageState.QueryString["name"];
        }
        else
        {
            await logger.LogError(LogFunction.Security, "Invalid Attempt To Access User Password Reset");
            NavigationManager.NavigateTo(NavigateUrl("")); // home page
        }
    }

    private async Task Reset()
    {
        validated = true;
        var interop = new Interop(JSRuntime);
        if (await interop.FormValid(form))
        {
            try
            {
                if (_username != string.Empty && _password != string.Empty && _confirm != string.Empty)
                {
                    if (_password == _confirm)
                    {
                        var user = new User
                        {
                            SiteId = PageState.Site.SiteId,
                            Username = _username,
                            Password = _password
                        };
                        user = await UserService.ResetPasswordAsync(user, PageState.QueryString["token"]);

                        if (user != null)
                        {
                            await logger.LogInformation("User Password Reset {Username}", _username);
                            NavigationManager.NavigateTo(NavigateUrl("login"));
                        }
                        else
                        {
                            await logger.LogError("Error Resetting User Password {Username}", _username);
                            AddModuleMessage(Localizer["Error.Password.ResetInfo"], MessageType.Error);
                        }
                    }
                    else
                    {
                        AddModuleMessage(Localizer["Message.Password.NoMatch"], MessageType.Warning);
                    }
                }
                else
                {
                    AddModuleMessage(Localizer["Message.Required.UserInfo"], MessageType.Warning);
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Resetting User Password {Username} {Error}", _username, ex.Message);
                AddModuleMessage(Localizer["Error.Password.Reset"], MessageType.Error);
            }
        }
        else
        {
            AddModuleMessage(SharedLocalizer["Message.InfoRequired"], MessageType.Warning);
        }
    }

    private void Cancel()
    {
        NavigationManager.NavigateTo(NavigateUrl(string.Empty));
    }

    private void TogglePassword()
	{
		if (_passwordtype == "password")
		{
			_passwordtype = "text";
			_togglepassword = SharedLocalizer["HidePassword"];
		}
		else
		{
			_passwordtype = "password";
			_togglepassword = SharedLocalizer["ShowPassword"];
		}
	}
}
