using HRD.LDAPService.JWT;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;

namespace HRD.LDAPService
{
    public static class LdapExtensions
    {
        public static LdapUser CheckAndAddGroupMembers(this PrincipalContext context, UserPrincipal userPrincipal, LdapUser ldapUser)
        {
            if (context == null || userPrincipal == null || ldapUser == null)
            {
                throw new Exception($"UserPrincipal failed");
            }

            if (ldapUser.RoleList?.Count == 0)
            {
                ldapUser.RoleList = new List<JwtRole>();
                return ldapUser;
            }

            try
            {
                List<Principal> userGroupList = userPrincipal.GetGroups().ToList(); // all groups of which the user is a direct member
                List<JwtRole> jwtRoleList = ldapUser.RoleList; //keep all possible Roles of the user
                List<JwtRole> fullRoleList = new List<JwtRole>();
                fullRoleList = fullRoleList.Union(jwtRoleList).ToList(); //add Roles from backend
                fullRoleList = fullRoleList.Union(JwtTokenConfig.JwtRoleList).ToList(); //add Roles from JwtTokenConfig.JwtRoleList

                ldapUser.RoleList = new List<JwtRole>();

                if (fullRoleList.Count > 0)
                {
                    foreach (JwtRole jwtRole in jwtRoleList)
                    {
                        if (userGroupList.Exists(userGroup => userGroup.Name == jwtRole.Group))
                        {
                            ldapUser.AddRole(jwtRole.Role);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ldapUser;
        }
    }
}