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

namespace DiplomovaPrace.Web.Admin.Services
{
	public class LoginService : ILoginService
	{
		private readonly NavigationManager navigationManager;
		private readonly ISecurityServiceContract securityServiceContract;
		private readonly JwtAuthenticationStateProvider authenticationStateProvider;

		public LoginService(
			NavigationManager navigationManager,
			ISecurityServiceContract securityServiceContract,
			JwtAuthenticationStateProvider authenticationStateProvider)
		{
			this.navigationManager = navigationManager;
			this.securityServiceContract = securityServiceContract;
			this.authenticationStateProvider = authenticationStateProvider;
		}

		public async Task<bool> LoginAdminAsync(LoginAccountIM loginAccount, string returnUrl)
		{
			AuthenticationResult result = await securityServiceContract.AuthenticateAdminAsync(loginAccount).ConfigureAwait(false);

			if (!string.IsNullOrEmpty(result.Token))
			{
				await authenticationStateProvider.SetTokenAsync(result.Token).ConfigureAwait(false);
				navigationManager.NavigateTo(returnUrl ?? "/"); // tuto bych presunul do LoginForm.razor.cs

				return true;
			}

			return false;
		}

		public async Task LogoutAdminAsync()
		{
			await authenticationStateProvider.SetTokenAsync(null).ConfigureAwait(false);

			navigationManager.NavigateTo("login");
		}

		public Task VerifyUserAsync(Guid authorizationToken)
		{
			throw new NotImplementedException();
		}
	}
}
