using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MTWorkHR.Application.Identity;
using MTWorkHR.Application.Mapper;
using MTWorkHR.Application.Models;
using MTWorkHR.Core.Global;
using MTWorkHR.Core.IRepositories;
using MTWorkHR.Core.UnitOfWork;
using MTWorkHR.Infrastructure.Entities;
using MTWorkHR.Application.Services.Interfaces;
using MTWorkHR.Core.Email;
using MTWorkHR.Core.Entities;
using MTWorkHR.Infrastructure.UnitOfWorks;
using System.Linq.Dynamic.Core;

namespace MTWorkHR.Application.Services
{
    public class ProjectService : BaseService<Project, ProjectDto, ProjectDto>, IProjectService
    {
        private readonly IUnitOfWork _unitOfWork;
        //private readonly AppSettingsConfiguration _configuration;
        //private readonly GlobalInfo _globalInfo;
        private readonly ITeamService _teamService;

        public ProjectService(IUnitOfWork unitOfWork, ITeamService teamService) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _teamService = teamService;
        }

        public override async Task<ProjectDto> GetById(long id)
        {
            var entity = await _unitOfWork.Project.GetByIdWithAllChildren(id);
            var response = MapperObject.Mapper.Map<ProjectDto>(entity);
           // if (response != null)
           //     response.ProjectTeamIds = response.ProjectTeams != null ? response.ProjectTeams?.Select(u => u.TeamId).ToList() : new List<long>();
            return response;
        }
        public override async Task<ProjectDto> Create(ProjectDto input)
        {
            var entity = MapperObject.Mapper.Map<Project>(input);

            if (entity is null)
            {
                throw new AppException(ExceptionEnum.MapperIssue);
            }
            entity.ProjectTeams = input.ProjectTeamIds?.Select(s => new ProjectTeam { TeamId = s, TeamName = _teamService.GetTeamName(s).Result }).ToList();

            var Project = await _unitOfWork.Project.AddAsync(entity);
            await _unitOfWork.CompleteAsync();

            var response = MapperObject.Mapper.Map<ProjectDto>(Project);
            response.ProjectTeamIds = input.ProjectTeamIds;
            return response;
        }

        public override async Task<ProjectDto> Update(ProjectDto input)
        {
            var entity = await _unitOfWork.Project.GetByIdWithAllChildren(input.Id);
            if (entity is null)
                throw new AppException(ExceptionEnum.RecordNotExist);
            entity.NameAr = input.NameAr;
            entity.NameEn = input.NameEn;
            var oldUsers = entity.ProjectTeams?.Select(s => s.TeamId);

            var NewItems = input.ProjectTeamIds?.Where(u => !oldUsers.Contains(u));
            var newProjectTeams = NewItems?.Select(s => new ProjectTeam { ProjectId = input.Id, TeamId = s, TeamName = _teamService.GetTeamName(s).Result}).ToList();
            var DeletedItems = oldUsers?.Where(u => !input.ProjectTeamIds.Contains(u));
            _unitOfWork.BeginTran();
            foreach (var delUser in DeletedItems)
            {
                var removeItem = entity.ProjectTeams?.FirstOrDefault(u => u.TeamId == delUser);
                if (removeItem != null) await _unitOfWork.ProjectTeam.DeleteAsync(removeItem);
            }
            foreach (var newteam in newProjectTeams)
            {
                await _unitOfWork.ProjectTeam.AddAsync(newteam);
            }

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

            var response = Mapper.MapperObject.Mapper.Map<ProjectDto>(entity);
            return response;
        }
        public override async Task<PagingResultDto<ProjectDto>> GetAll(PagingInputDto PagingInputDto)
        {
            var res = await _unitOfWork.Project.GetAllWithChildrenAsync();
            var query = res.Item1;
           
            if (PagingInputDto.HiddenFilter != null)
            {
                query = query.Where(PagingInputDto.HiddenFilter);
            }
            if (PagingInputDto.Filter != null)
            {
                var filter = PagingInputDto.Filter;
                query = query.Where(u => u.NameAr.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<ProjectDto>>(await page.ToListAsync());

            var tasks = await _unitOfWork.UserTask.GetAllWithChildrenAsync();


            foreach (var project in list)
            {
                var projectTasks = tasks.Item1.Where(a=> a.ProjectId == project.Id);
                var totalCount = (decimal)projectTasks.Count();
                if (totalCount > 0)
                {
                    decimal countDone = projectTasks.Count(a => a.TaskStatus.NameEn == "Done");
                    project.ProgressPercentage = countDone / totalCount;
                }
                else project.ProgressPercentage = 0;
            }

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

            return response;
        }

    }
}
