using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DocumentFormat.OpenXml.Drawing;
using NP.Utilities;
using pavesys_iRAP.Business;
using pavesys_iRAP.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace pavesys_iRAP.ViewModels
{
    public partial class PassRecoverPageViewModel : ViewModelBase
    {
        [ObservableProperty]
        private string email;

        [ObservableProperty]
        private string token;

        [ObservableProperty]
        private string password;
        [ObservableProperty]
        private string confirmPassword;

        [ObservableProperty]
        private bool showEmail = true;
        [ObservableProperty]
        private bool showToken = false;
        
        private async Task<bool> ValidateEmail() 
        {

            
            try
            {
                string emailPattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";

                Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
                Match match = regex.Match(Email);
                if (!Email.IsNullOrEmpty() && match.Success)//Regex.IsMatch(Email, emailPattern)
                    return true;
                else 
                {
                    await DialogHelper.ShowOkDialog("Error", "InvalidEmail");
                    return false;
                }
            }
            catch (Exception ex) {
                Debug.WriteLine(ex);
                return false;
            }
        }
        [RelayCommand]
        public async void NextEmail() 
        {
            if (!await ValidateEmail())
                return;
            if (!await AuthModule.ResetPassEmail(Email)) 
            {
                await DialogHelper.ShowOkDialog("Error", "FailToAuthenticate");
                return;
            }
            
            ShowToken = true;
          
            ShowEmail = false;


        }
        public async Task<bool> ValidatePass() 
        {
            if (Password != ConfirmPassword)
            {
                await DialogHelper.ShowOkDialog("Error", "DifferentPasswords");
                return false;
            }
            return true;
        }
        public async Task<bool> TryChangePassword() {
            
            if(await AuthModule.CheckAndChangePassword(Token,Password))
            {
                await DialogHelper.ShowOkDialog("Success", "PasswordChanged");
                return true;
            }
            await DialogHelper.ShowOkDialog("Error", "ErrorResettingPass");
            return false;
        }
    }
}
