using DataAccessLayer.Entities;
using DataAccessLayer.Filtering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer.Units
{
    public class UserRoleUnit : UnitOfWork<User>
    {

        public UserRoleUnit(ISDbContext context) : base(context)
        {
            _userRepository = new BaseRepository<User>(context);
            _roleRepository = new BaseRepository<Role>(context);
        }

        public async Task UpdateWithRolesAsync(User entity, IEnumerable<int> roleIds)
        {

            var user = await _userRepository.GetByIdAsync(entity.Id);


            foreach (var roleId in roleIds)
            {
                if (user.Roles.Any(x => x.Id == roleId)) continue;
                var role = await _roleRepository.GetByIdAsync(roleId);
                user.Roles.Add(role);
            }

            var toRemove = new List<Role>();
            foreach(var role in user.Roles)
            {
                if (!roleIds.Contains(role.Id))
                    toRemove.Add(role);
            }

            foreach (var roleToRemove in toRemove)
                user.Roles.Remove(roleToRemove);

            _userRepository.Update(user);
            await SaveAsync();
        }


        private BaseRepository<User> _userRepository;
        private BaseRepository<Role> _roleRepository;
    }
}
