using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VeterinaryContracts.StorageContracts;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.ViewModels;
using VeterinaryDatabaseImplement.Models;

namespace VeterinaryDatabaseImplement.Implements
{
	public class DoctorStorage : IDoctorStorage
	{
		public List<DoctorViewModel> GetFullList()
		{
			using var context = new VeterinaryDatabase();
			return context.Doctors
			.Select(x => x.GetViewModel)
		   .ToList();
		}
		public List<DoctorViewModel> GetFilteredList(DoctorSearchModel model)
		{
			if (string.IsNullOrEmpty(model.DoctorFIO) && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password) &&
				string.IsNullOrEmpty(model.DoctorFIO))
			{
				return new();
			}
			using var context = new VeterinaryDatabase();
			return context.Doctors
			.Where(x => (string.IsNullOrEmpty(model.DoctorFIO) || x.DoctorFIO.Contains(model.DoctorFIO) &&
						 (string.IsNullOrEmpty(model.Login) || x.DoctorFIO.Contains(model.Login)) &&
						 (string.IsNullOrEmpty(model.Password) || x.DoctorFIO.Contains(model.Password))))
		   .Select(x => x.GetViewModel)
		   .ToList();
		}
		public DoctorViewModel? GetElement(DoctorSearchModel model)
		{
			if (string.IsNullOrEmpty(model.DoctorFIO) && string.IsNullOrEmpty(model.Login) &&
			   !model.Id.HasValue)
			{
				return null;
			}
			using var context = new VeterinaryDatabase();
			return context.Doctors
			.FirstOrDefault(x => (string.IsNullOrEmpty(model.DoctorFIO) || x.DoctorFIO == model.DoctorFIO) &&
								 (!model.Id.HasValue || x.Id == model.Id) && (string.IsNullOrEmpty(model.Login) || x.Login == model.Login) &&
								 (string.IsNullOrEmpty(model.Password) || x.Password == model.Password))
			?.GetViewModel;
		}
		public DoctorViewModel? Insert(DoctorBindingModel model)
		{
			var newDoctor = Doctor.Create(model);
			if (newDoctor == null)
			{
				return null;
			}
			using var context = new VeterinaryDatabase();
			context.Doctors.Add(newDoctor);
			context.SaveChanges();
			return newDoctor.GetViewModel;
		}
		public DoctorViewModel? Update(DoctorBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var client = context.Doctors.FirstOrDefault(x => x.Id == model.Id);
			if (client == null)
			{
				return null;
			}
			client.Update(model);
			context.SaveChanges();
			return client.GetViewModel;
		}
		public DoctorViewModel? Delete(DoctorBindingModel model)
		{
			using var context = new VeterinaryDatabase();
			var element = context.Doctors.FirstOrDefault(rec => rec.Id == model.Id);
			if (element != null)
			{
				context.Doctors.Remove(element);
				context.SaveChanges();
				return element.GetViewModel;
			}
			return null;
		}
	}
}
