using Demo.Domain.Models;
using Demo.Data.Repository;

namespace Demo.Domain.UseCase
{
    public class GroupUseCase : IGroupUseCase
    {
		private readonly IUserRepository _repositoryUserImpl;
        private readonly IGroupRepository _repositoryGroupImpl;
        public GroupUseCase(IGroupRepository repositoryGroupImpl, IUserRepository repositoryUserImpl)
        {
            _repositoryGroupImpl = repositoryGroupImpl;
            _repositoryUserImpl = repositoryUserImpl;
        }

        public List<Group> GetAllGroups() => _repositoryGroupImpl.GetAllGroup()
        .Select(it => new Group{ID = it.ID, Name = it.Name}).ToList();

        public Group GetGroupById(int groupID)
        {
            GroupLocalEntity? groupLocalEntity = _repositoryGroupImpl.GetGroupById(groupID);
            if (groupLocalEntity == null) throw new Exception("bello");
            return new Group{ID = groupID, Name = groupLocalEntity.Name};
        }

        public List<GroupCon> GetAllGroupsWithUsers(){
            var groups = _repositoryGroupImpl.GetAllGroup().Select(it => new GroupCon { ID = it.ID, Name = it.Name }).ToList();
            var users = _repositoryUserImpl.GetAllUser().Select(it => new User{FIO = it.FIO, Guid = it.Guid, Group = new Group{ID = it.GroupID, Name = _repositoryGroupImpl.GetGroupById(it.GroupID).Name}}).ToList();
            foreach (var group in groups)
            {
                foreach (var user in users)
                {
                    if (user.Group.ID == group.ID){
                        group.Users.Add(user);
                    }
                }
            }
            return groups;
        }

        public bool CreateGroup(string Name){
            _repositoryGroupImpl.CreateGroup(Name);
            return true;
        }

        public Group UpdateGroup(Group group)
        {
            GroupLocalEntity groupLocalEntity = new GroupLocalEntity
            {
                ID = group.ID,
                Name = group.Name
            };
            GroupLocalEntity? result = _repositoryGroupImpl.UpdateGroup(groupLocalEntity);
            if (result == null)
            {
                throw new Exception("Не удалось обновить пользователя: пользователь не найден.");
            }
            return new Group
            {
                ID = result.ID,
                Name = result.Name
            };
        }

        public bool RemoveGroupByID(int userID) {
           return _repositoryGroupImpl.RemoveGroupByID(userID);
        }
    }
}