using GarmentFactoryContracts.BindingModels;
using GarmentFactoryContracts.ViewModels;
using GarmentFactoryDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;


namespace GarmentFactoryDatabaseImplement.Models
{
	[DataContract]
	public class Textile : ITextileModel
    {
		[DataMember]
		public int Id { get; set; }
		[DataMember]
		[Required]
        public string TextileName { get; set; } = string.Empty;
		[DataMember]
		[Required]
        public double Price { get; set; }
        private Dictionary<int, (IComponentModel, int)>? _textileComponents =
       null;
		[DataMember]
		[NotMapped]
        public Dictionary<int, (IComponentModel, int)> TextileComponents
        {
            get
            {
                if (_textileComponents == null)
                {
                    _textileComponents = Components
                    .ToDictionary(recPC => recPC.ComponentId, recPC =>
                   (recPC.Component as IComponentModel, recPC.Count));
                }
                return _textileComponents;
            }
        }
        [ForeignKey("TextileId")]
        public virtual List<TextileComponent> Components { get; set; } = new();
        [ForeignKey("TextileId")]
        public virtual List<Order> Orders { get; set; } = new();
        public static Textile Create(GarmentFactoryDatabase context,
       TextileBindingModel model)
        {
            return new Textile()
            {
                Id = model.Id,
                TextileName = model.TextileName,
                Price = model.Price,
                Components = model.TextileComponents.Select(x => new
               TextileComponent
                {
                    Component = context.Components.First(y => y.Id == x.Key),
                    Count = x.Value.Item2
                }).ToList()
            };
        }
        public void Update(TextileBindingModel model)
        {
            TextileName = model.TextileName;
            Price = model.Price;
        }
        public TextileViewModel GetViewModel => new()
        {
            Id = Id,
            TextileName = TextileName,
            Price = Price,
            TextileComponents = TextileComponents
        };
        public void UpdateComponents(GarmentFactoryDatabase context,
       TextileBindingModel model)
        {
            var textileComponents = context.TextileComponents.Where(rec =>
           rec.TextileId == model.Id).ToList();
            if (textileComponents != null && textileComponents.Count > 0)
            { // удалили те, которых нет в модели
                context.TextileComponents.RemoveRange(textileComponents.Where(rec
               => !model.TextileComponents.ContainsKey(rec.ComponentId)));
                context.SaveChanges();
                // обновили количество у существующих записей
                foreach (var updateComponent in textileComponents)
                {
                    updateComponent.Count =
                   model.TextileComponents[updateComponent.ComponentId].Item2;
                    model.TextileComponents.Remove(updateComponent.ComponentId);
                }
                context.SaveChanges();
            }
            var textile = context.Textiles.First(x => x.Id == Id);
            foreach (var tt in model.TextileComponents)
            {
                context.TextileComponents.Add(new TextileComponent
                {
                    Textile = textile,
                    Component = context.Components.First(x => x.Id == tt.Key),
                    Count = tt.Value.Item2
                });
                context.SaveChanges();
            }
            _textileComponents = null;
        }

    }
}
