using Contracts.BindingModels;
using Contracts.Converters;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseImplement.Models
{
	public class Sell : ISell
	{
		public Guid Id { get; set; }
		public DateTime DateSell { get; set; }
		public Guid? UserId { get; set; }
        private Dictionary<Guid, (IProduct, int)>? _sellProducts = null;
        public virtual User? User { get; set; }
        [DataMember]
        [NotMapped]
        public Dictionary<Guid, (IProduct, int)> PurchaseProducts
        {
            get
            {
                if (_sellProducts == null)
                {
                    _sellProducts = Products.ToDictionary(e => e.ProductId, e => (e.Product as IProduct, e.Count));
                }
                return _sellProducts;
            }
            set { }
        }
        [ForeignKey("SellId")]
        public virtual List<SellProducts> Products { get; set; } = new();
        public static Sell Create(Database context, SellBindingModel model)
		{
			return new Sell()
			{
				Id = model.Id,
				DateSell = model.DateSell,
                UserId = model.UserId,
			};
		}

		public SellBindingModel GetBindingModel => new()
		{
			Id = Id,
			DateSell = DateSell,
			UserId = UserId,
		};
        public SellViewModel GetViewModel => new()
        {
            Id = Id,
            DateSell = DateSell,
            UserId = UserId,

        };
        public static Sell ToSellFromView(SellViewModel model, Sell sell) => new()
		{
			Id = model.Id,
			DateSell = model.DateSell
		};

		public static Sell ToSellFromBinding(SellBindingModel model, Sell sell) => new()
		{
			Id = model.Id,
			DateSell = model.DateSell,
		};

		public void Update(SellBindingModel model)
		{
			if (model is null)
			{
				throw new ArgumentNullException("Update user: binding model is null");
			}

			DateSell = model.DateSell;
			UserId = model.UserId;
		}
		public void UpdateProducts(Database context, SellBindingModel model)
		{
            var sellProducts = context.SellProducts.Where(rec =>
            rec.Id == model.Id).ToList();
            if (sellProducts != null && sellProducts.Count > 0)
            { // удалили те, которых нет в модели
                context.SellProducts.RemoveRange(sellProducts.Where(rec
                => !model.SellProducts.ContainsKey(rec.ProductId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateProduct in sellProducts)
                {
                    updateProduct.Count = model.SellProducts[updateProduct.ProductId].Item2;
                    model.SellProducts.Remove(updateProduct.ProductId);
                }
                context.SaveChanges();
            }
        }
	}
}