using SoftwareInstallationDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;

namespace SoftwareInstallationDatabaseImplement.Models
{
    public class Package : IPackageModel
    {
        public int Id { get; set; }
        [Required]
        public string PackageName { get; set; } = string.Empty;
        [Required]
        public double Price { get; set; }
        private Dictionary<int, (IComponentModel, int)>? _packageComponents = null;

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

        [ForeignKey("PackageId")]
        public virtual List<PackageComponent> Components { get; set; } = new();
        [ForeignKey("PackageId")]
        public virtual List<Order> Orders { get; set; } = new();
        [ForeignKey("PackageId")]
        public virtual List<Shop> Shops { get; set; } = new();

        public static Package Create(SoftwareInstallationDatabase context, PackageBindingModel model)
        {
            return new Package()
            {
                Id = model.Id,
                PackageName = model.PackageName,
                Price = model.Price,
                Components = model.PackageComponents.Select(x => new PackageComponent
                {
                    Component = context.Components.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }
        public void Update(PackageBindingModel model)
        {
            PackageName = model.PackageName;
            Price = model.Price;
        }
        public PackageViewModel GetViewModel => new()
        {
            Id = Id,
            PackageName = PackageName,
            Price = Price,
            PackageComponents = PackageComponents
        };
        public void UpdateComponents(SoftwareInstallationDatabase context, PackageBindingModel model)
        {
            var packageComponents = context.PackageComponents
                .Where(rec => rec.PackageId == model.Id)
                .ToList();
            if (packageComponents != null && packageComponents.Count > 0)
            { // удалили те, которых нет в модели
                context.PackageComponents
                    .RemoveRange(packageComponents
                    .Where(rec => !model.PackageComponents
                                        .ContainsKey(rec.ComponentId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateComponent in packageComponents.Where(x => model.PackageComponents.ContainsKey(x.ComponentId)))
                {
                    updateComponent.Count = model.PackageComponents[updateComponent.ComponentId].Item2;
                    model.PackageComponents.Remove(updateComponent.ComponentId);
                }
                context.SaveChanges();
            }
            var package = context.Packages.First(x => x.Id == Id);
            foreach (var pc in model.PackageComponents)
            {
                context.PackageComponents.Add(new PackageComponent
                {
                    Package = package,
                    Component = context.Components.First(x => x.Id == pc.Key),
                    Count = pc.Value.Item2
                });
                context.SaveChanges();
            }
            _packageComponents = null;
        }
    }
}
