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 GuidanceStorage : IGuidanceStorage
	{
		public List<GuidanceViewModel> GetFullList()
		{
			using var context = new VetClinicDatabase();
			return context.Guidances.Include(x => x.Service).Select(x => x.GetViewModel).ToList();
		}
		public List<GuidanceViewModel> GetFilteredList(GuidanceSearchModel model)
		{

			using var context = new VetClinicDatabase();
			return context.Guidances.Include(x => x.Service).Where(x => (!model.Id.HasValue || model.Id == x.Id)
				&& (!model.ServiceId.HasValue || model.ServiceId == x.ServiceId) && (!model.DateFrom.HasValue || model.DateFrom <= x.Date)
				 && (!model.DateTo.HasValue || model.DateTo >= x.Date))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public GuidanceViewModel? GetElement(GuidanceSearchModel model)
		{
			using var context = new VetClinicDatabase();
			return context.Guidances.Include(x => x.Service).FirstOrDefault(x => (!model.Id.HasValue || model.Id == x.Id)
				&& (!model.ServiceId.HasValue || model.ServiceId == x.ServiceId) && (!model.DateFrom.HasValue || model.DateFrom <= x.Date)
				 && (!model.DateTo.HasValue || model.DateTo >= x.Date))?.GetViewModel;
		}
		public GuidanceViewModel? Insert(GuidanceBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var newGuidance = Guidance.Create(context, model);
			if (newGuidance == null)
			{
				return null;
			}
			context.Guidances.Add(newGuidance);
			context.SaveChanges();
			return newGuidance.GetViewModel;
		}
		public GuidanceViewModel? Update(GuidanceBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Guidances
			 .Include(x => x.Service)
			.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Guidances.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
		public GuidanceViewModel? Delete(GuidanceBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Guidances.FirstOrDefault(rec => rec.Id ==
		   model.Id);
			if (element != null)
			{
				context.Guidances.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}