using AbstractShopContracts.BindingModels;
using AbstractShopContracts.ViewModels;
using AbstractShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AbstractShopDatabaseImplement.Models
{
    public class Product : IProductModel
    {
        public int Id { get; set; }

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

        [Required]
        public double Price { get; set; }

        private Dictionary<int, (IComponentModel, int)>? _productComponents = null;

        [NotMapped]
        public Dictionary<int, (IComponentModel, int)> ProductComponents
        {
            get
            {
                if (_productComponents == null)
                {
                    _productComponents = Components
                            .ToDictionary(recPC => recPC.ComponentId, recPC => (recPC.Component as IComponentModel, recPC.Count));
                }
                return _productComponents;
            }
        }

        [ForeignKey("ProductId")]
        public virtual List<ProductComponent> Components { get; set; } = new();

        public static Product Create(AbstractShopDatabase context, ProductBindingModel model)
        {
            return new Product()
            {
                Id = model.Id,
                ProductName = model.ProductName,
                Price = model.Price,
                Components = model.ProductComponents.Select(x => new ProductComponent
                {
                    Component = context.Components.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }

        public void Update(ProductBindingModel model)
        {
            ProductName = model.ProductName;
            Price = model.Price;
        }

        public ProductViewModel GetViewModel => new()
        {
            Id = Id,
            ProductName = ProductName,
            Price = Price,
            ProductComponents = ProductComponents
        };

        public void UpdateComponents(AbstractShopDatabase context, ProductBindingModel model)
        {
            var productComponents = context.ProductComponents.Where(rec => rec.ProductId == model.Id).ToList();
            if (productComponents != null && productComponents.Count > 0)
            {   // удалили те, которых нет в модели
                context.ProductComponents.RemoveRange(productComponents.Where(rec => !model.ProductComponents.ContainsKey(rec.ComponentId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateComponent in productComponents)
                {
                    updateComponent.Count = model.ProductComponents[updateComponent.ComponentId].Item2;
                    model.ProductComponents.Remove(updateComponent.ComponentId);
                }
                context.SaveChanges();
            }
            var product = context.Products.First(x => x.Id == Id);
            foreach (var pc in model.ProductComponents)
            {
                context.ProductComponents.Add(new ProductComponent
                {
                    Product = product,
                    Component = context.Components.First(x => x.Id == pc.Key),
                    Count = pc.Value.Item2
                });
                context.SaveChanges();
            }
            _productComponents = null;
        }
    }
}