using VetClinicDataModels.Models;
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 VetClinicContracts.BindingModels;
using VetClinicContracts.ViewModels;
using System.Collections;
using System.ComponentModel;

namespace VetClinicDataBaseImplement.Models
{
	public class Animal : IAnimalModel
	{
		public int Id { get; set; }
		[Required]
		public int AdminId { get; set; }

		[Required]
		public string AnimalName { get; set; } = string.Empty;

		[Required]
		public string Family { get; set; } = string.Empty;


		[ForeignKey("AnimalId")]
		public virtual List<Vaccination> Vaccinations { get; set; } = new();

		public virtual Admin Admin { get; set; }

		[ForeignKey("AnimalId")]
		public virtual List<VisitAnimal> Visits { get; set; } = new();


		[ForeignKey("AnimalId")]
		public virtual List<MedicineAnimal> Medicines { get; set; } = new();

		public Dictionary<int, IVisitModel>? _visitAnimals = null;

		[NotMapped]
		public Dictionary<int, IVisitModel> VisitAnimals
		{
			get
			{
				if (_visitAnimals == null)
				{
					_visitAnimals = Visits.ToDictionary(recPC => recPC.VisitId, recPC =>
				   recPC.Visit as IVisitModel);
				}
				return _visitAnimals;
			}
		}
		public static Animal? Create(VetClinicDatabase context, AnimalBindingModel? model)
		{
			if (model == null)
			{
				return null;
			}
			return new Animal()
			{
				Id = model.Id,
				AdminId = model.AdminId,
				AnimalName = model.AnimalName,
				Family = model.Family,
				Visits = model.VisitAnimals.Select(x => new VisitAnimal
				{
					Visit = context.Visits.First(y => y.Id == x.Key)
				}).ToList()
			};
		}
		public void Update(AnimalBindingModel? model)
		{
			if (model == null)
			{
				return;
			}
			AnimalName = model.AnimalName;
			Family = model.Family;
		}
		public AnimalViewModel GetViewModel => new()
		{
			Id = Id,
			VisitAnimals = VisitAnimals,
			AdminId = AdminId,
			AnimalName = AnimalName,
			Family = Family

		};
		public void UpdateVisits(VetClinicDatabase context, AnimalBindingModel model)
		{
			var visitAnimals = context.VisitAnimals.Where(rec => rec.AnimalId == model.Id).ToList();
			if (visitAnimals != null)
			{ 
				context.VisitAnimals.RemoveRange(visitAnimals.Where(rec => !model.VisitAnimals.ContainsKey(rec.VisitId)));
				context.SaveChanges();
				foreach (var visit in visitAnimals)
				{
					model.VisitAnimals.Remove(visit.VisitId);
				}
				context.SaveChanges();
			}
			var animal = context.Animals.First(x => x.Id == Id);
			foreach (var pc in model.VisitAnimals)
			{
				context.VisitAnimals.Add(new VisitAnimal
				{
					Animal = animal,
					Visit = context.Visits.First(x => x.Id == pc.Key),

				});
				context.SaveChanges();
			}
			_visitAnimals = null;
		}
	}
}
