using AutoMapper; using AutoMapper.QueryableExtensions; 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 WeeklyTimeSpanService { private readonly ApplicationDbContext _dbContext; private readonly IMapper _mapper; public WeeklyTimeSpanService(ApplicationDbContext dbContext, IMapper mapper) { _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext)); _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); } public async Task> GetAllWeeklyTimeSpans() { var wts = await _dbContext.WeeklyTimeSpans.Include(x => x.Pauses).ToListAsync(); return _mapper.Map, List>(wts); } public async Task GetWeeklyTimeSpan(int weeklytimespanId) { var wts = await _dbContext.WeeklyTimeSpans.Include(x => x.Pauses).Where(x => x.Id == weeklytimespanId).FirstOrDefaultAsync(); return _mapper.Map(wts); } public async Task> GetPausesOfWeeklyTimeSpan(int weeklytimespanId) { var pauses = await _dbContext.WeeklyTimeSpans.Include(x => x.Pauses).Where(x => x.Id == weeklytimespanId).FirstOrDefaultAsync(); return _mapper.Map, List>(pauses.Pauses); } public async Task GetWeeklyTimeSpanByStartdate(DateTime startTime) { var wts = await _dbContext.WeeklyTimeSpans.Include(x => x.Pauses).Where(x => x.Startdate.Date.Equals(startTime.Date)).ToListAsync(); return _mapper.Map, WeeklyTimeSpanDTO>(wts); } public async Task AddWeeklyTimeSpan(WeeklyTimeSpanDTO weeklytimespan) { var wts = _mapper.Map(weeklytimespan); var obj = await _dbContext.WeeklyTimeSpans.AddAsync(wts); await _dbContext.SaveChangesAsync(); return _mapper.Map(obj.Entity); } public async Task DeleteWeeklyTimeSpan(int weeklytimespanId) { try { var item = await _dbContext.WeeklyTimeSpans.Where(x => x.Id == weeklytimespanId).FirstOrDefaultAsync(); _dbContext.WeeklyTimeSpans.Remove(item); await _dbContext.SaveChangesAsync(); return true; } catch (Exception) { return false; } } public async Task UpdateWeeklyTimeSpan(WeeklyTimeSpanDTO weeklytimespan) { var wts = _mapper.Map(weeklytimespan); wts.Id = weeklytimespan.Id; _dbContext.WeeklyTimeSpans.Update(wts); await _dbContext.SaveChangesAsync(); var newwts = await _dbContext.WeeklyTimeSpans.Where(x => x.Id == weeklytimespan.Id).FirstOrDefaultAsync(); return _mapper.Map(newwts); } } }