using Microsoft.EntityFrameworkCore.Storage;
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.SearchModels;
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; }
		public virtual Doctor? Doctor { get; private set; }

		[Required]
		public DateTime DateCreate { 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)
		{
			var justMedications = model.DrugMedications.Select(x => new DrugMedication
			{
				Medication = context.Medications.First(y => y.Id == x.Key)
			}).ToList();
			double prc=0;
			foreach (var justMedication in justMedications)
			{
				prc += justMedication.Medication.Price;
			}
			return new Drug()
			{
				Id = model.Id,
				DrugName = model.DrugName,
				
				Count = model.Count,
				DoctorId = model.DoctorId,
				Medications = justMedications,
				Price = prc,
				DateCreate= model.DateCreate
			};
		}
		// цену считает неверно
		public void Update( DrugBindingModel model)
		{
			
			DrugName = model.DrugName;
		}
		public DrugViewModel GetViewModel => new()
		{
			Id = Id,
			DrugName = DrugName,
			Price = Price,
			Count= Count,
			DoctorId=DoctorId,
			DateCreate = DateCreate,
			DrugMedications = DrugMedications
		};
		public void UpdateMedications(VeterinaryDatabase context, DrugBindingModel model)
		{
			var drugMedications = context.DrugMedications.Where(rec => rec.DrugId == model.Id).ToList();
			var list = new List <int>();
			foreach (var rec in model.DrugMedications)
			{
				list.Add(rec.Key);
			}
			//var tmp = model.DrugMedications;
			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;
			var justMedications = list.Select(x => new DrugMedication
			{
				Medication = context.Medications.First(y => y.Id == x)
			}).ToList();
			double pric = 0;
			foreach (var justMedication in justMedications)
			{
				pric += justMedication.Medication.Price;
			}
			Price = pric;
			context.SaveChanges();

		}

	}
}
