using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Kimuser.Domain;
using Kimuser.Domain.SystemUsers;
using Kimuser.Infrastructure.Repositories;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Kimuser.Services
{
    public class ProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<User> _claimsFactory;
        private readonly UserManager<User> _userManager;
        private readonly IUserRepository<SystemUser> _systemUserRepository;

        public ProfileService(IUserClaimsPrincipalFactory<User> claimsFactory, UserManager<User> userManager, IUserRepository<SystemUser> systemUserRepository)
        {
            _claimsFactory = claimsFactory;
            _userManager = userManager;
            _systemUserRepository = systemUserRepository;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            if (user == null)
            {
                throw new ArgumentException("");
            }

            var principal = await _claimsFactory.CreateAsync(user);
            var claims = principal.Claims.ToList();




            //Thêm các claim khác tại đây
            //claims.Add(new System.Security.Claims.Claim("MyProfileID", user.Id));
            var systemUser = await _systemUserRepository.Query().FirstOrDefaultAsync(s => s.Id == user.Id);
            var roles = String.Join(',', (await _userManager.GetRolesAsync(systemUser)).ToList());
            if (systemUser != null && systemUser.Id > 0)
            {
                claims.Add(new Claim("BranchId", systemUser.BranchId > 0 ? systemUser.BranchId.ToString() : ""));
                claims.Add(new Claim("FullName", !string.IsNullOrEmpty(systemUser.FullName) ? systemUser.FullName : ""));
                claims.Add(new Claim("Roles", roles));
            }
            //var customer = _customerFounder.GetById(user.Id);
            //if (customer != null && customer.Id > 0)
            //{
            //    claims.Add(new Claim("DcId", ""));
            //    claims.Add(new Claim("UserType", "2"));
            //    claims.Add(new Claim("FullName", customer.Name));
            //}
            context.IssuedClaims = claims;
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            var sub = context.Subject.GetSubjectId();
            var user = await _userManager.FindByIdAsync(sub);
            context.IsActive = user != null;
        }
    }
}
