using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DTOToEntity
{
    public class LangueService : IService<LangueDTO>
    {
        private readonly UnitOfWork _context = new UnitOfWork();
        public LangueService() { }

        public LangueService(StubbedContext context)
        {
            this._context = new UnitOfWork(context);
        }
        public async Task<LangueDTO> Add(LangueDTO langue)
        {
            var langueEntity = langue.ToEntity();
             _context.LangueRepository.Insert(langueEntity);
            await _context.SaveChangesAsync();
            return langue;
            
        }

        public async Task<LangueDTO> Delete(object id)
        {
            var langue = _context.LangueRepository.GetById(id);
            if (langue != null)
            {
                _context.LangueRepository.Delete(langue);
                 await _context.SaveChangesAsync();
            }
            else { 
                throw new Exception("Langue not found");
            }
            return langue.ToDTO();
        }

        public async Task<LangueDTO> GetById(object id)
        {
            var langue = _context.LangueRepository.GetById(id);
            if (langue == null)
            {
                throw new Exception("Langue not found");
            }
            return langue.ToDTO();

        }

        public async Task<PageResponse<LangueDTO>> Gets(int index,int count)
        {
            IEnumerable<LangueEntity> langues = _context.LangueRepository.GetItems(index, count);
            return new PageResponse<LangueDTO>(langues.ToList().Select(l => l.ToDTO()), _context.LangueRepository.GetItems(0, 1000000000).Count());
        }

        public async Task<LangueDTO> Update(LangueDTO langue)
        {
            LangueEntity? langueToUpdate = _context.LangueRepository.GetById(langue.name);
            if (langueToUpdate == null)
            {
                throw new Exception("Langue not found");
            }
            //langueToUpdate.vocabularys = (ICollection<VocabularyEntity>)langue.vocabularys.Select(v => v.ToEntity());
            return langueToUpdate.ToDTO();
        }
    }
}
