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 PauseService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly IMapper _mapper;

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

        public async Task<List<PauseDTO>> GetAllPauses()
        {
            var pauses = await _dbContext.Pauses.Include(x => x.WeeklyTimeSpan).ToListAsync();
            return _mapper.Map<List<Pause>, List<PauseDTO>>(pauses);
        }

        public async Task<PauseDTO> AddPause(string userId, PauseDTO pause)
        {
            var wts = await _dbContext.WeeklyTimeSpans.Include(x => x.Pauses).Where(x => x.UserId == userId && x.Id == pause.WeeklyTimeSpanId).FirstOrDefaultAsync();
            
            if (wts == null)
            {
                throw new Exception("Not found");
            }
            
            var pauseEntity = _mapper.Map<PauseDTO, Pause>(pause);
            pauseEntity.WeeklyTimeSpanId = pause.WeeklyTimeSpanId;
            var obj = _dbContext.Pauses.Add(pauseEntity);
            await _dbContext.SaveChangesAsync();
            return _mapper.Map<Pause, PauseDTO>(obj.Entity);
        }

        public async Task<PauseDTO> GetPause(int pauseId)
        {
            var pause = await _dbContext.Pauses.Where(x => x.Id == pauseId).FirstOrDefaultAsync();
            return _mapper.Map<Pause, PauseDTO>(pause);
        }

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

        public async Task<PauseDTO> UpdatePause(PauseDTO pause)
        {
            var pauseEntity = _mapper.Map<PauseDTO, Pause>(pause);
            pauseEntity.Id = pause.Id;
            _dbContext.Pauses.Update(pauseEntity);
            await _dbContext.SaveChangesAsync();
            var newPause = await _dbContext.Pauses.Where(x => x.Id == pause.Id).FirstOrDefaultAsync();
            return _mapper.Map<Pause, PauseDTO>(newPause);
        }
    }
}
