// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;

namespace SelmoStudio.Hmi.Server.SelmoHmi.Authentication.Service
{
    public class AuthenticationStateService : IAuthenticationStateService, IDisposable
    {
        private readonly AuthenticationStateProvider _authenticationStateProvider;

        public event Func<Task>? AuthenticationStateChanged;

        public AuthenticationStateService(AuthenticationStateProvider authenticationStateProvider)
        {
            _authenticationStateProvider = authenticationStateProvider;
            _authenticationStateProvider.AuthenticationStateChanged += async (t) => await NotifyAuthenticationStateChangedAsync();
        }

        public async Task NotifyAuthenticationStateChangedAsync()
        {
            if (AuthenticationStateChanged != null)
            {
                await AuthenticationStateChanged.Invoke();
            }
        }

        public async Task<bool> IsAuthenticatedAsync()
        {
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();

            return authState.User.Identity?.Name != null;
        }

        public async Task<ClaimsPrincipal> GetCurrentUserAsync()
        {
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();

            return authState.User;
        }

        public void Dispose()
        {
            _authenticationStateProvider.AuthenticationStateChanged -= async (t) => await NotifyAuthenticationStateChangedAsync();
        }
    }
}