using DressAtelierContracts.BindingModels;
using DressAtelierContracts.ViewModels;
using DressAtelierDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace DressAtelierDatabaseImplementation.Models
{
    public class Dress : IDressModel
    {
        public int ID { get; private set; }
        [Required]
        public string DressName { get; private set; } = string.Empty;
        
        [Required]
        public double Price { get; private set; }

        private Dictionary<int, (IMaterialModel, int)>? _dressMaterials = null;

        [NotMapped]
        public Dictionary<int, (IMaterialModel, int)> DressComponents
        {
            get
            {
                if (_dressMaterials == null)
                {
                    _dressMaterials = Materials.ToDictionary(recPC => recPC.MaterialID, recPC =>(recPC.Material as IMaterialModel, recPC.Count));
                }
                return _dressMaterials;
            }
        }
        [ForeignKey("DressID")]
        public virtual List<DressMaterial> Materials { get; set; } = new();

        [ForeignKey("DressID")]
        public virtual List<Order> Orders { get; set; } = new();

        public static Dress Create(DressAtelierDatabase context, DressBindingModel model)
        {
            return new Dress()
            {
                ID = model.ID,
                DressName = model.DressName,
                Price = model.Price,
                Materials = model.DressComponents.Select(x => new DressMaterial
                {
                    Material = context.Materials.First(y => y.ID == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }

        public void Update(DressBindingModel model)
        {
            DressName = model.DressName;
            Price = model.Price;
        }

        public DressViewModel GetViewModel => new()
        {
            ID = ID,
            DressName = DressName,
            Price = Price,
            DressComponents = DressComponents
        };

        public void UpdateComponents(DressAtelierDatabase context, DressBindingModel model)
        {
            var dressMaterials = context.DressMaterials.Where(rec =>  rec.DressID == model.ID).ToList();
            if (dressMaterials != null && dressMaterials.Count > 0)
            { // удалили те, которых нет в модели
                context.DressMaterials.RemoveRange(dressMaterials.Where(rec => !model.DressComponents.ContainsKey(rec.MaterialID)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateComponent in dressMaterials)
                {
                    updateComponent.Count = model.DressComponents[updateComponent.MaterialID].Item2;
                    model.DressComponents.Remove(updateComponent.MaterialID);
                }
                context.SaveChanges();
            }
            var product = context.Dresses.First(x => x.ID == ID);
            foreach (var pc in model.DressComponents)
            {
                context.DressMaterials.Add(new DressMaterial
                {
                    Dress = product,
                    Material = context.Materials.First(x => x.ID == pc.Key),
                    Count = pc.Value.Item2
                });
                context.SaveChanges();
            }
            _dressMaterials = null;
        }

    }
}
