using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace FishFactoryDatabaseImplement.Models
{
    public class Canned : ICannedModel
    {
        public int Id { get; set; }

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

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

        private Dictionary<int, (IIngredientModel, int)>? _cannedIngredients = null;

        [NotMapped]
        public Dictionary<int, (IIngredientModel, int)> CannedIngredients
        {
            get
            {
                if (_cannedIngredients == null)
                {
                    _cannedIngredients = Ingredients
                            .ToDictionary(recPC => recPC.IngredientId, recPC => (recPC.Ingredient as IIngredientModel, recPC.Count));
                }
                return _cannedIngredients;
            }
        }

        [ForeignKey("CannedId")]
        public virtual List<CannedIngredient> Ingredients { get; set; } = new();

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

        public static Canned Create(FishFactoryDatabase context, CannedBindingModel model)
        {
            return new Canned()
            {
                Id = model.Id,
                CannedName = model.CannedName,
                Price = model.Price,
                Ingredients = model.CannedIngredients.Select(x => new CannedIngredient
                {
                    Ingredient = context.Ingredients.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }

        public void Update(CannedBindingModel model)
        {
            CannedName = model.CannedName;
            Price = model.Price;
        }

        public CannedViewModel GetViewModel => new()
        {
            Id = Id,
            CannedName = CannedName,
            Price = Price,
            CannedIngredients = CannedIngredients
        };

        public void UpdateIngredients(FishFactoryDatabase context, CannedBindingModel model)
        {
            var cannedIngredients = context.CannedIngredients.Where(rec => rec.CannedId == model.Id).ToList();
            if (cannedIngredients != null && cannedIngredients.Count > 0)
            {   // удалили те, которых нет в модели
                context.CannedIngredients.RemoveRange(cannedIngredients.Where(rec => !model.CannedIngredients.ContainsKey(rec.IngredientId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateIngredient in cannedIngredients)
                {
                    updateIngredient.Count = model.CannedIngredients[updateIngredient.IngredientId].Item2;
                    model.CannedIngredients.Remove(updateIngredient.IngredientId);
                }
                context.SaveChanges();
            }
            var canned = context.CannedList.First(x => x.Id == Id);
            foreach (var cd in model.CannedIngredients)
            {
                context.CannedIngredients.Add(new CannedIngredient
                {
                    Canned = canned,
                    Ingredient = context.Ingredients.First(x => x.Id == cd.Key),
                    Count = cd.Value.Item2
                });
                context.SaveChanges();
            }
            _cannedIngredients = null;
        }
    }
}