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

namespace MTWorkHR.Application.Services
{
    public class UserTaskService : BaseService<UserTask, UserTaskDto, UserTaskDto>, IUserTaskService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IFileService _fileService;
        private readonly GlobalInfo _globalInfo;
        private readonly IUserService _userService;

        public UserTaskService(IUnitOfWork unitOfWork, IFileService fileService, GlobalInfo globalInfo, IUserService userService) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _fileService = fileService;
            _globalInfo = globalInfo;
            _userService = userService;
        }


        public override async Task<UserTaskDto> GetById(long id)
        {
            var entity = await _unitOfWork.UserTask.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<UserTaskDto>(entity);
            await GetUserData(response);
            return response;
        }
        public async Task<UserTaskDto> GetByUserId(string userId)
        {
            var entity = await _unitOfWork.UserTask.GetByUserIdWithAllChildren(userId);
           
            var response = MapperObject.Mapper.Map<UserTaskDto>(entity);
            await GetUserData(response);

            return response;
        }

        public async Task<PagingResultDto<UserTaskAllDto>> GetAll(UserTaskPagingInputDto PagingInputDto)
        {
            var res = await _unitOfWork.UserTask.GetAllWithChildrenAsync();
            var query = res.Item1;

            if (_globalInfo.UserType != UserTypeEnum.Business)
            {
                query = query.Where(m => m.AssignedUserId == _globalInfo.UserId);

            }
            if (PagingInputDto.HiddenFilter != null)
            {
                query = query.Where(PagingInputDto.HiddenFilter);
            }
            if (PagingInputDto.Filter != null)
            {
                var filter = PagingInputDto.Filter;
                query = query.Where(u => u.Title.Contains(filter) || u.Description.Contains(filter));
            }
            if (PagingInputDto.ProjectId != null)
            {
                query = query.Where(u => u.ProjectId == PagingInputDto.ProjectId);
            }
            if (PagingInputDto.StatusId != null)
            {
                query = query.Where(u => u.StatusId == PagingInputDto.StatusId);
            }
            if (PagingInputDto.PriorityId != null)
            {
                query = query.Where(u => u.Priority == (PriorityEnum)PagingInputDto.PriorityId);
            }
            if (PagingInputDto.AssignedUserId != null)
            {
                query = query.Where(u => u.AssignedUserId == PagingInputDto.AssignedUserId);
            }
            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<UserTaskAllDto>>(await page.ToListAsync());
            foreach (var item in list)
            {
                if (item.AssignedUserId != null)
                {
                    var user = await _userService.GetUserWithAttachmentById(item.AssignedUserId);
                    if(user != null)
                    {
                        item.AssignedUserName = user.FirstName + " " + user.LastName;
                        var image = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9); 
                        item.ProfileImage = image != null ? image.FilePath:"";
                    }
                }
            }
            var response = new PagingResultDto<UserTaskAllDto>
            {
                Result = list,
                Total = total
            };

            return response;
        }

        public override async Task<UserTaskDto> Create(UserTaskDto input)
        {
            if (input.TaskAttachments?.Count > 0)
            {
                var attachs = input.TaskAttachments.ToList();
                _fileService.CopyFileToCloud(ref attachs);
            }

            var entity = MapperObject.Mapper.Map<UserTask>(input);
            if (entity is null)
            {
                throw new AppException(ExceptionEnum.MapperIssue);
            }

            var task = await _unitOfWork.UserTask.AddAsync(entity);
            await _unitOfWork.CompleteAsync();

            var response = MapperObject.Mapper.Map<UserTaskDto>(task);
            await GetUserData(response);
            return response;
        }

        private async Task GetUserData(UserTaskDto response)
        {
            if (response.AssignedUserId != null)
            {
                var user = await _userService.GetUserWithAttachmentById(response.AssignedUserId);
                if (user != null)
                {
                    response.AssignedUserName = user.FirstName + " " + user.LastName;
                    var image = user.UserAttachments?.FirstOrDefault(a => a.AttachmentTypeId == 9);
                    response.ProfileImage = image != null ? image.FilePath : "";
                }
            }
        }

        public override async Task<UserTaskDto> Update(UserTaskDto input)
        {
            var entity = await _unitOfWork.UserTask.GetByIdAsync(input.Id);

            if (entity == null)
                throw new AppException(ExceptionEnum.RecordNotExist);

            MapperObject.Mapper.Map(input, entity, typeof(UserTaskDto), typeof(UserTask));

            await _unitOfWork.CompleteAsync();
            var response = Mapper.MapperObject.Mapper.Map<UserTaskDto>(entity);
            await GetUserData(response);

            return response;
        }

        public async Task ChangeStatus(long taskId, int statusId)
        {
            var entity = await _unitOfWork.UserTask.GetByIdAsync(taskId);
            if (entity == null)
                throw new AppException(ExceptionEnum.RecordNotExist);
            entity.StatusId = statusId;
           
            await _unitOfWork.CompleteAsync();
        }
    }
}
