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

namespace VeterinaryDatabaseImplement.Models
{
    public class Drug : IDrugModel
	{
		public int Id { get; set; }
		[Required]
		public string DrugName { get; set; } = string.Empty;
		[Required]
		public double Price { get; set; }
		[Required]
		public int Count { get; set; }
		[Required]
		public int DoctorId { get; private set; }
		private Dictionary<int, IMedicationModel>? _drugMedications = null;
		[NotMapped]
		public Dictionary<int, IMedicationModel> DrugMedications
		{
			get
			{
				if (_drugMedications == null)
				{
					_drugMedications = Medications
					.ToDictionary(recPC => recPC.MedicationId, recPC =>
				   (recPC.Medication as IMedicationModel));
				}
				return _drugMedications;
			}
		}
		[ForeignKey("DrugId")]
		public virtual List<DrugMedication> Medications { get; set; } = new();
		[ForeignKey("DrugId")]
		public virtual List<Purchase> Purchases { get; set; } = new();
		public static Drug Create(VeterinaryDatabase context, DrugBindingModel model)
		{
			return new Drug()
			{
				Id = model.Id,
				DrugName = model.DrugName,
				Price = model.Price,
				Count = model.Count,
				DoctorId = model.DoctorId,
				Medications = model.DrugMedications.Select(x => new DrugMedication
				{
					Medication = context.Medications.First(y => y.Id == x.Key)
				}).ToList()
			};
		}
		public void Update(DrugBindingModel model)
		{
			DrugName = model.DrugName;
			Price = model.Price;
		}
		public DrugViewModel GetViewModel => new()
		{
			Id = Id,
			DrugName = DrugName,
			Price = Price,
			DoctorId=DoctorId,
			DrugMedications = DrugMedications
		};
		public void UpdateMedications(VeterinaryDatabase context, DrugBindingModel model)
		{
			var drugMedications = context.DrugMedications.Where(rec => rec.DrugId == model.Id).ToList();
			if (drugMedications != null && drugMedications.Count > 0)
			{
				context.DrugMedications.RemoveRange(drugMedications.Where(rec => !model.DrugMedications.ContainsKey(rec.MedicationId)));
				context.SaveChanges();
				foreach (var updateMedication in drugMedications)
				{
					model.DrugMedications.Remove(updateMedication.MedicationId);
				}
				context.SaveChanges();
			}
			var drug = context.Drugs.First(x => x.Id == Id);
			foreach (var pc in model.DrugMedications)
			{
				context.DrugMedications.Add(new DrugMedication
				{
					Drug = drug,
					Medication = context.Medications.First(x => x.Id == pc.Key)
				});
				context.SaveChanges();
			}
			_drugMedications = null;
		}

	}
}
