using Contracts.BindingModels;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DatabaseImplement.Models
{
    public class Supplier : ISupplier
    {
        public Guid Id { get; set; }
        [Required]
        public string Name { get; set; } = string.Empty;
        [Required]
        public int Deals { get; set; }
        private Dictionary<Guid, (IProduct, int)>? _availibleProducts = null;
        [NotMapped]
        public Dictionary<Guid, (IProduct, int)> AvailibleProducts
        {
            get
            {
                if (_availibleProducts == null)
                {
                    _availibleProducts = Products
                    .ToDictionary(recPC => recPC.Id, recPC =>
                    (recPC.Product as IProduct, recPC.Count));
                }
                return _availibleProducts;
            }
        }
        [ForeignKey("SupplierId")]
        public virtual List<SupplierProduct> Products { get; set; } = new();

        public static Supplier Create(Database context, SupplierBindingModel model)
        {
            return new Supplier()
            {
                Id = model.Id,
                Name = model.Name,
                Deals = model.Deals,
                Products = model.AvailibleProducts.Select(x => new
                SupplierProduct
                {
                    Product = context.Products.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }
        public void Update(Database context, SupplierBindingModel model)
        {
            Name = model.Name;
            Deals = model.Deals;
            Debug.WriteLine(model.AvailibleProducts.Keys);
            Products = model.AvailibleProducts.Select(x => new
            SupplierProduct
            {
                Product = context.Products.First(y => y.Id == x.Value.Item1.Id),
                Count = x.Value.Item2
            }).ToList();
        }
        public SupplierViewModel GetViewModel
        {
            get
            {
                var context = new Database();
                return new()
                {
                    Id = Id,
                    Name = Name,
                    AvailibleProducts = AvailibleProducts,
                    Deals = Deals,
                };
            }
        }
        public void UpdateProducts(Database context, SupplierBindingModel model)
        {
            var test = context.SupplierProducts.ToList();
            var supplierProducts = context.SupplierProducts.Where(rec => rec.SupplierId == model.Id).ToList();
            if (supplierProducts != null && supplierProducts.Count > model.AvailibleProducts.Count)
            {
                var newList = new List<SupplierProduct>();
                var trueCount = model.AvailibleProducts.Count;
                for (int i = 0; i < trueCount; i++)
                {
                    newList.Add(supplierProducts[i]);
                }
                supplierProducts = newList;
            }
            if (supplierProducts != null && supplierProducts.Count > 0)
            { // удалили те, которых нет в модели
                foreach (var item in supplierProducts)
                {
                    bool flag = false;
                    foreach (var product in model.AvailibleProducts)
                    {
                        if (product.Value.Item1.Id == item.ProductId)
                        {
                            flag = true;
                        }
                    }
                    if (!flag)
                    {
                        context.SupplierProducts.Remove(item);
                    }
                }
                context.SaveChanges();
                //обновили количество у существующих записей, затем удалили
                foreach (var updateProduct in supplierProducts)
                {
                    try
                    {
                        updateProduct.Count = model.AvailibleProducts[updateProduct.Id].Item2;
                        model.AvailibleProducts.Remove(updateProduct.Id);
                    }
                    catch (Exception ex) { }
                }
                context.SaveChanges();
            }
            var supplier = context.Suppliers.First(x => x.Id == Id);
            // тут всё дюпается, тут должны добавляться те которые остались в модели
            foreach (var pc in model.AvailibleProducts)
            {
                context.SupplierProducts.Add(new SupplierProduct
                {
                    Supplier = supplier,
                    Product = context.Products.First(x => x.Id == pc.Value.Item1.Id),
                    Count = pc.Value.Item2
                });
                context.SaveChanges();
            }
            _availibleProducts = null;
        }
    }
}
