using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VetClinicContracts.BindingModels;
using VetClinicContracts.SearchModels;
using VetClinicContracts.StoragesContracts;
using VetClinicContracts.ViewModels;
using VetClinicDataBaseImplement.Models;

namespace VetClinicDataBaseImplement.Implements
{
	public class VaccinationStorage : IVaccinationStorage
	{
		public List<VaccinationViewModel> GetFullList()
		{
			using var context = new VetClinicDatabase();
			return context.Vaccinations.Include(x => x.Animal).Select(x => x.GetViewModel).ToList();
		}
		public List<VaccinationViewModel> GetFilteredList(VaccinationSearchModel model)
		{

			using var context = new VetClinicDatabase();
			return context.Vaccinations.Include(x => x.Animal).Where(x => (!model.Id.HasValue || model.Id == x.Id)
				&& (!model.AnimalId.HasValue || model.AnimalId == x.AnimalId) && (!model.DateFrom.HasValue || model.DateFrom <= x.DateStamp)
				 && (!model.DateTo.HasValue || model.DateTo >= x.DateStamp))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public VaccinationViewModel? GetElement(VaccinationSearchModel model)
		{
			using var context = new VetClinicDatabase();
			return context.Vaccinations.Include(x => x.Animal).FirstOrDefault(x => (!model.Id.HasValue || model.Id == x.Id)
				&& (!model.AnimalId.HasValue || model.AnimalId == x.AnimalId) && (!model.DateFrom.HasValue || model.DateFrom <= x.DateStamp)
				 && (!model.DateTo.HasValue || model.DateTo >= x.DateStamp))?.GetViewModel;
		}
		public VaccinationViewModel? Insert(VaccinationBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var newVaccination = Vaccination.Create(context, model);
			if (newVaccination == null)
			{
				return null;
			}
			context.Vaccinations.Add(newVaccination);
			context.SaveChanges();
			return newVaccination.GetViewModel;
		}
		public VaccinationViewModel? Update(VaccinationBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Vaccinations
			 .Include(x => x.Animal)
			.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Vaccinations.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
		public VaccinationViewModel? Delete(VaccinationBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Vaccinations.FirstOrDefault(rec => rec.Id ==
		   model.Id);
			if (element != null)
			{
				context.Vaccinations.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
