using SecuritySystemDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;

namespace SecuritySystemDatabaseImplement.Models
{
    public class Secure : ISecureModel
    {
        public int Id { get; set; }
        [Required]
        public string SecureName { get; set; } = string.Empty;
        [Required]
        public double Price { get; set; }
        private Dictionary<int, (IComponentModel, int)>? _productComponents =
       null;
        [NotMapped]
        public Dictionary<int, (IComponentModel, int)> SecureComponents
        {
            get
            {
                if (_productComponents == null)
                {
                    _productComponents = Components
                    .ToDictionary(recPC => recPC.ComponentId, recPC =>
                   (recPC.Component as IComponentModel, recPC.Count));
                }
                return _productComponents;
            }
        }
        [ForeignKey("SecureId")]
        public virtual List<SecureComponent> Components { get; set; } = new();
        [ForeignKey("SecureId")]
        public virtual List<Order> Orders { get; set; } = new();
        public static Secure Create(SecuritySystemDatabase context, SecureBindingModel model)
        {
            return new Secure()
            {
                Id = model.Id,
                SecureName = model.SecureName,
                Price = model.Price,
                Components = model.SecureComponents.Select(x => new
               SecureComponent
                {
                    Component = context.Components.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }
        public void Update(SecureBindingModel model)
        {
            SecureName = model.SecureName;
            Price = model.Price;
        }
        public SecureViewModel GetViewModel => new()
        {
            Id = Id,
            SecureName = SecureName,
            Price = Price,
            SecureComponents = SecureComponents
        };
        public void UpdateComponents(SecuritySystemDatabase context,
       SecureBindingModel model)
        {
            var productComponents = context.SecureComponents.Where(rec =>
           rec.SecureId == model.Id).ToList();
            if (productComponents != null && productComponents.Count > 0)
            { // удалили те, которых нет в модели
                context.SecureComponents.RemoveRange(productComponents.Where(rec
               => !model.SecureComponents.ContainsKey(rec.ComponentId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateComponent in productComponents)
                {
                    updateComponent.Count =
                   model.SecureComponents[updateComponent.ComponentId].Item2;
                    model.SecureComponents.Remove(updateComponent.ComponentId);
                }
                context.SaveChanges();
            }
            var product = context.Secures.First(x => x.Id == Id);
            foreach (var pc in model.SecureComponents)
            {
                context.SecureComponents.Add(new SecureComponent
                {
                    Secure = product,
                    Component = context.Components.First(x => x.Id == pc.Key),
                    Count = pc.Value.Item2
                });
                context.SaveChanges();
            }
            _productComponents = null;
        }
    }

}
