using AutoMapper;
using HanyadikHetVan.Data;
using HanyadikHetVan.Data.Entities;
using HanyadikHetVan.DTO;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HanyadikHetVan.Services
{
    public class FunFactService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly IMapper _mapper;

        public FunFactService(ApplicationDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }

        public async Task<List<FunFactDTO>> GetFunFactOfWeeklyTimeSpan(int weeklytimespanId)
        {
            var funfact = await _dbContext.FunFacts.Where(x => x.WeeklyTimeSpanId == weeklytimespanId).ToListAsync();
            return _mapper.Map<List<FunFact>, List<FunFactDTO>>(funfact);
        }

        public async Task<double> GetFunFactorOfFunFact(int funfactId)
        {
            var funfact = await _dbContext.FunFacts.Where(x => x.Id == funfactId).FirstOrDefaultAsync();
            return funfact.FunFactor;
        }

        public async Task<bool> DeleteFunFact(int funfactId)
        {
            try
            {
                var item = await _dbContext.FunFacts.Where(x => x.Id == funfactId).FirstOrDefaultAsync();
                _dbContext.FunFacts.Remove(item);
                await _dbContext.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public async Task<FunFactDTO> UpdateFunFact(int funfactId, FunFactDTO funfact)
        {
            var funfactentity = _mapper.Map<FunFactDTO, FunFact>(funfact);
            funfactentity.Id = funfactId;
            _dbContext.FunFacts.Update(funfactentity);
            await _dbContext.SaveChangesAsync();
            var newff = await _dbContext.FunFacts.Where(x => x.Id == funfactId).FirstOrDefaultAsync();
            return _mapper.Map<FunFact, FunFactDTO>(newff);
        }
    }
}
