// Copyright © Selmo Technology GmbH. All Rights Reserved

using Microsoft.AspNetCore.Components.Authorization;
using SelmoStudio.Hmi.Plugin.Services;
using System.Security.Claims;

namespace SelmoStudio.Hmi.Server.Db.Authentication.Service
{
    public class SelmoAuthenticationStateProvider : AuthenticationStateProvider
    {
        private ICachingService _cachingService;

        public SelmoAuthenticationStateProvider(ICachingService cachingService)
        {
            _cachingService = cachingService;
        }

        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var claims = await _cachingService.GetClaimsAsync();
            var identity = new ClaimsIdentity(claims, "jwt");
            var user = new ClaimsPrincipal(identity);
            return await Task.FromResult(new AuthenticationState(user));
        }

        public void ChangeUser()
        {
            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
    }
}