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 PharmacistStorage : IPharmacistStorage
	{
		public List<PharmacistViewModel> GetFullList()
		{
			using var context = new VetClinicDatabase();
			return context.Pharmacists
			.Select(x => x.GetViewModel)
		   .ToList();
		}
		public List<PharmacistViewModel> GetFilteredList(PharmacistSearchModel model)
		{
			if (string.IsNullOrEmpty(model.PharmacistFIO) && string.IsNullOrEmpty(model.Email) &&
				string.IsNullOrEmpty(model.Password))
			{
				return new();
			}
			using var context = new VetClinicDatabase();
			return context.Pharmacists
			.Where(x => (string.IsNullOrEmpty(model.PharmacistFIO) || x.PharmacistFIO.Contains(model.PharmacistFIO) &&
						 string.IsNullOrEmpty(model.Email) || x.Email.Contains(model.Email) &&
						 string.IsNullOrEmpty(model.Password) || x.Password.Contains(model.Password)))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public PharmacistViewModel? GetElement(PharmacistSearchModel model)
		{
			if (string.IsNullOrEmpty(model.PharmacistFIO) && string.IsNullOrEmpty(model.Email) &&
			   !model.Id.HasValue)
			{
				return null;
			}
			using var context = new VetClinicDatabase();
			return context.Pharmacists
			.FirstOrDefault(x => (string.IsNullOrEmpty(model.PharmacistFIO) || x.PharmacistFIO == model.PharmacistFIO) &&
								 (!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) &&
								 (string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
			?.GetViewModel;
		}
		public PharmacistViewModel? Insert(PharmacistBindingModel model)
		{
			var newPharmacist = Pharmacist.Create(model);
			if (newPharmacist == null)
			{
				return null;
			}
			using var context = new VetClinicDatabase();
			context.Pharmacists.Add(newPharmacist);
			context.SaveChanges();
			return newPharmacist.GetViewModel;
		}
		public PharmacistViewModel? Update(PharmacistBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var pharmacist = context.Pharmacists.FirstOrDefault(x => x.Id == model.Id);
			if (pharmacist == null)
			{
				return null;
			}
			pharmacist.Update(model);
			context.SaveChanges();
			return pharmacist.GetViewModel;
		}
		public PharmacistViewModel? Delete(PharmacistBindingModel model)
		{
			using var context = new VetClinicDatabase();
			var element = context.Pharmacists.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Pharmacists.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
