using Azure;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using MTWorkHR.Core.Entities.Base;
using MTWorkHR.Core.IDto;
using MTWorkHR.Core.IRepositories.Base;
using MTWorkHR.Infrastructure.DBContext;
using System.Linq;
using System.Linq.Dynamic.Core;

namespace MTWorkHR.Infrastructure.Repositories
{
    public class Repository<T> : IRepository<T> where T : Entity
    {
        protected readonly HRDataContext _context;
        private readonly DbSet<T> dbSet;

        public Repository(HRDataContext context)
        {
            _context = context;
            dbSet = context.Set<T>();
        }
        public async Task<T> AddAsync(T entity)
        {
            await _context.AddAsync(entity);
            await _context.SaveChangesAsync();
            return entity;
        }

        public async Task<IList<T>> AddRangeAsync(IList<T> entities)
        {
            await dbSet.AddRangeAsync(entities);
            return entities;
        }

        public async Task DeleteAsync(T entity)
        {
            dbSet.Remove(entity);
        }

        public async Task DeleteRangeAsync(IEnumerable<T> entities)
        {
            dbSet.RemoveRange(entities);
        }

        public async Task<Tuple<ICollection<T>, int>> GetAllAsync()
        {
            var query = dbSet.AsQueryable();
            var total = await query.CountAsync();

            return new Tuple<ICollection<T>, int>(await query.ToListAsync(), total);
        }

        public virtual async Task<Tuple<ICollection<T>, int>> GetAllAsync(IPagingInputDto pagingInputDto)
        {
            var query = dbSet.AsQueryable();

            if (pagingInputDto.HiddenFilter != null)
            {
                query = query.Where(pagingInputDto.HiddenFilter);
            }

            if (pagingInputDto.Filter != null)
            {
                var props = typeof(T).GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(FilterAttribute)));
                var condition = "";
                foreach (var p in props)
                {
                    condition = (condition == "" ? condition : condition + " || ") + p.Name + ".Contains(@0)";
                }

                query = query.Where(condition, pagingInputDto.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();

            return new Tuple<ICollection<T>, int>(await page.ToListAsync(), total);
            throw new NotImplementedException();
        }

        public async Task<T> GetByIdAsync(long id)
        {
            return await _context.Set<T>().FindAsync(id);
        }
    }
}
