
@page "/DT_WORK_FORCE_edit_password/{id:guid}"
@inject ReAct_PME.WebUI.ServicesUI.ApiService ApiService
@inject ReAct_PME.WebUI.ServicesUI.AuthService AuthService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
@inject IToastService ToastService
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@inject HttpClient Http
@using Blazored.Toast.Configuration;
@using Blazored.Toast.Services;
@using Microsoft.AspNetCore.Components.Authorization;
@using System.Text.RegularExpressions;

<h3 class="text-center my-4">Modification du mot de passe</h3>

@if (item == null)
{
    <p>Chargement...</p>
}
else
{
    <div class="container">
        <form>
			<div class="form-group row">
				<label for="USERNAME" class="col-sm-3 col-form-label">User Name* : </label>
				<div class="col-sm-9">
					<input id="USERNAME" @bind="item.USERNAME" class="form-control" maxlength="255" disabled/>
				</div>
			</div>
            <div class="form-group row">
                <label for="PASSWORD" class="col-sm-3 col-form-label">Password* : </label>
                <div class="col-sm-9">
                    <input id="PASSWORD" @bind="item.PASSWORD" class="form-control" maxlength="255" />
                </div>
            </div>
            <div class="form-group row">
                <label for="MAIL_PASSWORD" class="col-sm-3 col-form-label">Email Password* : </label>
                <div class="col-sm-9">
                    <input id="PASSWORD" @bind="item.MAIL_PASSWORD" class="form-control" maxlength="255" />
                </div>
            </div>
            <br />
            <div class="form-group">
                <div class="button-container justify-content-end">
                    <button type="button" class="btn btn-action btn-primary btn-compact3" @onclick="UpdateItem">Enregistrer</button>
                    <button type="button" class="btn btn-action btn-secondary btn-compact" @onclick="Cancel">Annuler</button>
                </div>
            </div>
        </form>
    </div>
}

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

	private Domain.DT_WORK_FORCE_DTO? item;

    protected override async Task OnInitializedAsync()
    {
        #region Vérification si utilisateur est connecté et s''il a les droits

        var bOk = await PagesInitializer.VerifConnexionAndRules<Domain.DT_WORK_FORCE_DTO>(AuthenticationStateProvider, Navigation, Http, ToastService, $"api/DT_WORK_FORCE_DTO/password/{Id}", HttpMethod.Put, new Domain.DT_WORK_FORCE_DTO() );
        if (!bOk)
            return;

        #endregion

		item = await ApiService.GetByIdAsync<Domain.DT_WORK_FORCE_DTO>($"api/DT_WORK_FORCE_DTO/{Id}");
        item!.PASSWORD = "";
        item!.MAIL_PASSWORD = "";
    }


    private async Task UpdateItem()
    {
        if (item != null)
        {
            try
            {
                if(!VerifValidPassword())
                {
                    ToastService.ShowError($"Erreur : Le contenu du mot de passe doit répondre aux exigences de l'organisation", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                    return;
                }
                
                bool b = await ApiService.UpdateAsync($"api/DT_WORK_FORCE_DTO/password/{Id}", item);
                if(b)
                {
                    ToastService.ShowSuccess("Modification réussie !", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                    await Task.Delay(2000);
                    Navigation.NavigateTo($"/dt_work_force_edit/{Id}", forceLoad: true);
                }
                else
                {
                    ToastService.ShowError($"Erreur : Modification impossible.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                }
            }
            catch(Exception ex)
            {
                ToastService.ShowError($"Erreur : {ex.Message}", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
            }
        }
    }


    private void Cancel()
    {
        Navigation.NavigateTo("/dt_work_force_list");
    }

    private bool VerifValidPassword()
    {
        bool bReturn = true;
        string password = item!.PASSWORD;

        if (password.Trim().Length == 0)
        {
            bReturn = false;
        }
        else
        {
            /* Exemple de Mot de passe (à adapter) */
            /* 8 caractères minimum, donc 1 majuscule + 1 chiffre + 1 caractère spécial */
            //string pattern = @"^(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$";
            //bReturn = Regex.IsMatch(password, pattern);
        }
        return bReturn;
    }
}


