using Microsoft.EntityFrameworkCore;
using MTWorkHR.Application.Identity;
using MTWorkHR.Application.Mapper;
using MTWorkHR.Application.Models;
using MTWorkHR.Core.Global;
using MTWorkHR.Core.UnitOfWork;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Entities;
using System.Linq.Dynamic.Core;

namespace MTWorkHR.Application.Services
{
    public class MeetingService : BaseService<Meeting, MeetingDto, MeetingDto>, IMeetingService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IUserService _userService;
        private readonly GlobalInfo _globalInfo;

        public MeetingService(IUnitOfWork unitOfWork, IUserService userService, GlobalInfo globalInfo) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _userService = userService;
            _globalInfo = globalInfo;
        }

        public override async Task<MeetingDto> GetById(long id)
        {
            var entity = await _unitOfWork.Meeting.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<MeetingDto>(entity);
            if (response != null)
                response.MeetingUserIds = response.MeetingUsers != null ? response.MeetingUsers?.Select(u => u.AssignedUserId).ToList() : new List<string>();
            return response;
        }
       
        public override async Task<MeetingDto> Create(MeetingDto input)
        {
            var entity = MapperObject.Mapper.Map<Meeting>(input);

            if (entity is null)
            {
                throw new AppException(ExceptionEnum.MapperIssue);
            }
            entity.MeetingUsers = input.MeetingUserIds?.Select(s => new MeetingUser { AssignedUserId = s, AssignedUserName = _userService.GetUserFullName(s).Result }).ToList();

            var team = await _unitOfWork.Meeting.AddAsync(entity);
            await _unitOfWork.CompleteAsync();

            var response = MapperObject.Mapper.Map<MeetingDto>(team);
            response.MeetingUserIds = input.MeetingUserIds;
            return response;
        }

        public override async Task<MeetingDto> Update(MeetingDto input)
        {
            var entity = await _unitOfWork.Meeting.GetByIdWithAllChildren(input.Id);
            if (entity is null)
                throw new AppException(ExceptionEnum.RecordNotExist);
            entity.Description = input.Description;
            entity.Location = input.Location;
            entity.Title = input.Title;
            entity.MeetingLink = input.MeetingLink;
            entity.MeetingDate = input.MeetingDate;
            entity.StartTime = input.StartTime;
            entity.EndTime = input.EndTime;
            entity.RepeatId = input.RepeatId;
            var oldUsers = entity.MeetingUsers?.Select(s => s.AssignedUserId);

            var NewItems = input.MeetingUserIds?.Where(u => !oldUsers.Contains(u));
            var newMeetingUsers = NewItems?.Select(s => new MeetingUser { MeetingId = input.Id, AssignedUserId = s, AssignedUserName = _userService.GetUserFullName(s).Result }).ToList();
            var DeletedItems = oldUsers?.Where(u => !input.MeetingUserIds.Contains(u));
            _unitOfWork.BeginTran();
            foreach (var delUser in DeletedItems)
            {
                var removeItem = entity.MeetingUsers?.FirstOrDefault(u => u.AssignedUserId == delUser);
                if (removeItem != null) await _unitOfWork.MeetingUser.DeleteAsync(removeItem);
            }
            foreach (var newUsr in newMeetingUsers)
            {
                await _unitOfWork.MeetingUser.AddAsync(newUsr);
            }

            await _unitOfWork.CompleteAsync();
            _unitOfWork.CommitTran();

            var response = Mapper.MapperObject.Mapper.Map<MeetingDto>(entity);
            return response;
        }
        public override async Task<PagingResultDto<MeetingDto>> GetAll(PagingInputDto PagingInputDto)
        {
            var res = await _unitOfWork.Meeting.GetAllWithChildrenAsync();
            var query = res.Item1;

            if (_globalInfo.UserType != UserTypeEnum.Business)
            {
                query = query.Where(m => m.MeetingUsers != null && m.MeetingUsers.Count > 0 && m.MeetingUsers.Count(u=> u.AssignedUserId == _globalInfo.UserId) > 0);

            }
            if (PagingInputDto.Filter != null)
            {
                var filter = PagingInputDto.Filter;
                query = query.Where(u => u.Title.Contains(filter) || u.Description!.Contains(filter));
            }

            var order = query.OrderBy(PagingInputDto.OrderByField + " " + PagingInputDto.OrderType);

            var page = order.Skip((PagingInputDto.PageNumber * PagingInputDto.PageSize) - PagingInputDto.PageSize).Take(PagingInputDto.PageSize);

            var total = await query.CountAsync();

            var list = MapperObject.Mapper
                .Map<IList<MeetingDto>>(await page.ToListAsync());

            var response = new PagingResultDto<MeetingDto>
            {
                Result = list,
                Total = total
            };

            return response;
        }

        //public override async Task Delete(long id)
        //{
        //    var entity = await _unitOfWork.Meeting.GetByIdAsync(id);
        //    await _unitOfWork.Meeting.DeleteAsync(entity);
        //}



    }
}