using DbConnectionLibrairie;
using Entities;
using ManagerInterfaces;
using Microsoft.EntityFrameworkCore;
using Model;
using OrderCriterias;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityManagers
{
    public class ChapterEntityManager(MyDbContext dbContext) : IChapterManager<ChapterEntity>
    {
        MyDbContext dbContext = dbContext;

        public async Task<ChapterEntity> addChapter(ChapterEntity chapter)
        {
            var tmp = await dbContext.Chapters.Where(c => c.Equals(chapter)).FirstOrDefaultAsync();
            if (tmp != null) // <=> he already exist
            {
                return tmp!;
            }
            dbContext.Chapters.Add(chapter);
            await dbContext.SaveChangesAsync();
            return await dbContext.Chapters.Where(c => c.Equals(chapter)).FirstAsync();
        }

        public async Task<ChapterEntity?> getChapter(uint id)
        {
            return await dbContext.Chapters.Where(c => c.Id == id).FirstOrDefaultAsync();
        }

        public async Task<(int nbPages, IEnumerable<ChapterEntity>? chapters)> getChapters(int nb, int count, ChapterOrderCriteria orderCriteria = ChapterOrderCriteria.ById)
        {
            int nbEl = getNbElements();
            if (nb < 0 || count < 0 || nb > nbEl / count) return await Task.FromResult<(int nbPages, IEnumerable<ChapterEntity>? chapters)>((nbEl / count, null));
            var tmp = dbContext.Chapters;
            switch (orderCriteria)
            {
                case ChapterOrderCriteria.ById:
                    tmp.OrderBy(a => a.Id);
                    break;
                case ChapterOrderCriteria.ByName:
                    tmp.OrderBy(a => a.Name);
                    break;
            }
            return await Task.FromResult<(int nbPages, IEnumerable<ChapterEntity>? chapters)>((nbEl / count, tmp.Skip((nb - 1) * count).Take(count)));
        }

        public int getNbElements()
        {
            return dbContext.Chapters.CountAsync().Result;
        }

        public async Task<ChapterEntity?> removeChapter(ChapterEntity chapter)
        {
            var tmp = dbContext.Chapters.Where(a => a.Equals(chapter)).FirstOrDefaultAsync().Result;
            if (tmp == null) return await Task.FromResult<ChapterEntity?>(tmp);
            dbContext.Chapters.Remove(tmp);
            await dbContext.SaveChangesAsync();
            return await Task.FromResult<ChapterEntity?>(tmp);
        }

        public async Task<ChapterEntity?> removeChapter(uint id)
        {
            var tmp = getChapter(id).Result;
            if (tmp == null) return await Task.FromResult<ChapterEntity?>(tmp);
            dbContext.Chapters.Remove(tmp);
            await dbContext.SaveChangesAsync();
            return await Task.FromResult<ChapterEntity?>(tmp);
        }
    }
}
