using System.Threading.Tasks;
using DiplomovaPrace.Contracts.Security;
using DiplomovaPrace.Contracts.Security.InputModels;
using DiplomovaPrace.Contracts.Security.ViewModels;
using Microsoft.AspNetCore.Components;

namespace DiplomovaPrace.Web.Admin.Services
{
	public class SecurityService : ISecurityService
	{
		private readonly ISecurityServiceContract securityServiceContract;
		private readonly NavigationManager navigationManager;

		public SecurityService(ISecurityServiceContract securityServiceContract, NavigationManager navigationManager)
		{
			this.securityServiceContract = securityServiceContract;
			this.navigationManager = navigationManager;
		}

		public async Task RecoverForgottenPasswordAsync(ForgottenPasswordIM inputModel)
		{
			await securityServiceContract.RecoverForgottenPasswordAsync(inputModel).ConfigureAwait(false);

			navigationManager.NavigateTo("login");
		}

		//TO DO: Implementovat validaci existence emailu (nejspíše zbytečné pro mé učely)
		public async Task RegisterAccountAsync(RegisterAccountIM inputModel)
		{
			await securityServiceContract.RegisterAccountAsync(inputModel).ConfigureAwait(false);

			navigationManager.NavigateTo("login");
		}

		public async Task PasswordResetAsync(PasswordResetIM inputModel)
		{
			await securityServiceContract.PasswordResetAsync(inputModel).ConfigureAwait(false);

			navigationManager.NavigateTo("login");
		}

		public async Task ValidateTokenAsync(string token)
		{
			PasswordResetTokenIM inputModel = new() { Token = token };
			TokenValidationResult result = await securityServiceContract.ValidatePasswordResetTokenAsync(inputModel).ConfigureAwait(false);

			// Pokud není token validní, tak přesměruji na login (nesmí dojít k restartování hesla)
			if (!result.IsValid)
			{
				navigationManager.NavigateTo("login");
			}
		}

		public async Task<bool> ChangePasswordAsync(PasswordChangeIM inputModel)
		{
			PasswordChangeResult result = await securityServiceContract.PasswordChangeAsync(inputModel).ConfigureAwait(false);

			return result.IsSuccessful;
		}
	}
}
