using ComputerShopContracts.BindingModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using ComputerShopDataModels.Enums;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Models;

namespace ComputerShopDatabaseImplement.Models
{
    internal class Order : IOrderModel
    {
        public int Id { get; private set; }
        [Required]
        public double Sum { get; private set; }
        [Required]
        public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
        [Required]
        public DateTime DateCreate { get; private set; } = DateTime.Now;

        public DateTime? DateImplement { get; private set; }

        [ForeignKey("OrderId")]
        private Dictionary<int, (IAssemblyModel, int)>? _orderAssembliess = null;

        public Dictionary<int, (IAssemblyModel, int)> OrderAssemblies
		{
            get
            {
                if (_orderAssembliess == null)
                {
					_orderAssembliess = Assemblies
					.ToDictionary(recPC => recPC.AssemblyId, recPC =>
                    (recPC.Assembly as IAssemblyModel, recPC.Count));
                }
                return _orderAssembliess;
            }
        }

		[ForeignKey("OrderId")]
		public virtual List<OrderAssembly> Assemblies { get; set; } = new();
		[ForeignKey("OrderId")]
		public virtual List<Supply>? Supplies { get; set; } = new();

		[Required]
        public int ClientId { get; set; }
		public virtual Client? Client { get; set; }
		public static Order? Create(ComputerShopDatabase context, OrderBindingModel model)
        {
            if (model == null)
            {
                return null;
            }
            var order_comp = model.OrderAssemblies.Select(x => new
                OrderAssembly
            {
                Assembly = context.Assemblies.First(y => y.Id == x.Key),
                Count = x.Value.Item2
            }).ToList();


            return new Order()
            {
                Id = model.Id,
                Sum = model.Sum,
                Status = model.Status,
                DateCreate = model.DateCreate,
                DateImplement = model.DateImplement,
                ClientId = model.ClientId,
				Assemblies = order_comp
            };
        }

        public void Update(OrderBindingModel model)
        {
            if (model == null)
            {
                return;
            }
            Status = model.Status;
            DateImplement = model.DateImplement;
            Sum = model.Sum;
        }
        public OrderViewModel GetViewModel => new()
        {
            Id = Id,
            Sum = Sum,
            Status = Status,
            DateCreate = DateCreate,
            DateImplement = DateImplement,
			OrderAssemblies = OrderAssemblies,
            ClientId = ClientId
        };

		public void UpdateAssemblies(ComputerShopDatabase context, OrderBindingModel model)
		{
			var assemblyComponents = context.AssemblyComponents.Where(rec => rec.Id == model.Id).ToList();
			if (assemblyComponents != null && assemblyComponents.Count > 0)
			{ // удалили те, которых нет в модели
				context.AssemblyComponents.RemoveRange(assemblyComponents.Where(rec
				=> !model.OrderAssemblies.ContainsKey(rec.AssemblyId)));
				context.SaveChanges();
				// обновили количество у существующих записей
				foreach (var updateComponent in assemblyComponents)
				{
					updateComponent.Count = model.OrderAssemblies[updateComponent.AssemblyId].Item2;
					model.OrderAssemblies.Remove(updateComponent.AssemblyId);
				}
				context.SaveChanges();
			}
			var assembly = context.Orders.First(x => x.Id == Id);
			foreach (var pc in model.OrderAssemblies)
			{
				context.OrderAssemblies.Add(new OrderAssembly
				{
					Order = assembly,
					Assembly = context.Assemblies.First(x => x.Id == pc.Key),
					Count = pc.Value.Item2
				});
				context.SaveChanges();
			}
			_orderAssembliess = null;
		}
	}
}
