

using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Aurora.Infrastructure.User;

namespace Aurora.Common.User
{
    public class UserContextProvider : IUserContextProvider
    {
        readonly IHttpContextAccessor _httpContextAccessor;
        readonly IUsersCache _usersCache;
        public UserContextProvider(IHttpContextAccessor httpContextAccessor, IUsersCache usersCache)
        {
            _httpContextAccessor = httpContextAccessor;
            _usersCache = usersCache;
        }

        public IUserContext GetUserContext()
        {
            IUserContext currentUser = new UserContext();
            if (_httpContextAccessor.HttpContext == null) //cap
            {
                currentUser.UserCode = "cap";
                currentUser.UserName = "cap";
            }
            else if (_httpContextAccessor.HttpContext.User != null &&
                _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) //external
            {
                ClaimsPrincipal claimsPrincipal = _httpContextAccessor.HttpContext.User;
                var subject = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Subject);

                var subjectRole = claimsPrincipal.Claims.FirstOrDefault(w => w.Type == JwtClaimTypes.Role);
                currentUser = GetCurrentUserFromRedis(subject.Value, subjectRole.Value);
            }
            else  //internal
            {
                currentUser.UserCode = "internal";
                currentUser.UserName = "internal";
            }
            return currentUser;
        }

        private IUserContext GetCurrentUserFromRedis(string usercode, string tenantCode)
        {
            // var redisUserInfo = new CacheRedis(RedisDBType.User, _configuration).GetJSON<CurrentUserInfo>($"{tenantCode}:{usercode}");
            return new UserContext();
            // return redisUserInfo;
        }
    }
}