using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VetClinicDataModels.Models;
using VetClinicContracts.BindingModels;
using VetClinicContracts.ViewModels;

namespace VetClinicDataBaseImplement.Models
{
	public class Medicine : IMedicineModel
	{
		public int Id { get; set; }
		[Required]
		public string MedicineName { get; set; } = string.Empty;
		[Required]
		public int PharmacistId { get; set; }
		public virtual Pharmacist Pharmacist { get; private set; }
		[Required]
		public double Price { get; set; }
		private Dictionary<int, IAnimalModel>? _medicineAnimals =
	   null;
		[NotMapped]
		public Dictionary<int, IAnimalModel> MedicineAnimals
		{
			get
			{
				if (_medicineAnimals == null)
				{
					_medicineAnimals = Animals
					.ToDictionary(recPC => recPC.AnimalId, recPC =>
				   recPC.Animal as IAnimalModel);
				}
				return _medicineAnimals;
			}
		}
		[ForeignKey("MedicineId")]
		public virtual List<MedicineAnimal> Animals { get; set; } = new();
		[ForeignKey("MedicineId")]
		public virtual List<ServiceMedicine> Services { get; set; } = new();
		public static Medicine Create(VetClinicDatabase context,
	   MedicineBindingModel model)
		{
			return new Medicine()
			{
				Id = model.Id,
				MedicineName = model.MedicineName,
				Price = model.Price,
				Animals = model.MedicineAnimals.Select(x => new
			   MedicineAnimal
				{
					Animal = context.Animals.First(y => y.Id == x.Key),
				}).ToList(),
				Pharmacist = context.Pharmacists.First(x => x.Id == model.PharmacistId)
			};
		}
		public void Update(MedicineBindingModel model)
		{
			MedicineName = model.MedicineName;
			Price = model.Price;
		}
		public MedicineViewModel GetViewModel => new()
		{
			Id = Id,
			MedicineName = MedicineName,
			Price = Price,
			MedicineAnimals = MedicineAnimals,
			PharmacistFIO = Pharmacist.PharmacistFIO
		};
		public void UpdateAnimals(VetClinicDatabase context,
	   MedicineBindingModel model)
		{
			if (model.MedicineAnimals == null)
				return;
			var medicineAnimals = context.MedicineAnimals.Where(rec =>
		   rec.MedicineId == model.Id).ToList();
			if (medicineAnimals != null && medicineAnimals.Count > 0)
			{
				context.MedicineAnimals.RemoveRange(medicineAnimals.Where(rec
=> !model.MedicineAnimals.ContainsKey(rec.AnimalId)));

				context.SaveChanges();
			}
			var medicine = context.Medicines.First(x => x.Id == Id);
			foreach (var pc in model.MedicineAnimals)
			{
				context.MedicineAnimals.Add(new MedicineAnimal
				{
					Medicine = medicine,
					Animal = context.Animals.First(x => x.Id == pc.Key),
				});
				context.SaveChanges();
			}
			_medicineAnimals = null;
		}
	}
}
