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

namespace CaseAccountingDataBaseImplement.Models
{
    public class Deal : IDealModel
    {
        public int Id { get; set; }

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

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

        [Required]
        public DateTime Date { get; set; }

        [Required]
        public int UserId { get; set; }

        public virtual User User { get; set; } = new();

        [ForeignKey("DealId")]
        public virtual List<CaseDeal> CaseDeals { get; set; } = new();

        private Dictionary<int, ICaseModel>? _cases;

        [NotMapped]
        public Dictionary<int, ICaseModel> Cases 
        { 
            get
            {
                if (_cases == null)
                {
                    _cases = CaseDeals.ToDictionary(
                        x => x.CaseId, x => x.Case as ICaseModel);
                }
                return _cases;
            } 
        }

        [ForeignKey("DealId")]
        public virtual List<DealContract> Contracts { get; set; } = new();

        public static Deal? Create(CaseAccountingDatabase context, DealBindingModel? model)
        {
            if (model == null)
            {
                return null;
            }
            return new Deal()
            {
                Id = model.Id,
                Subject = model.Subject,
                Responsibilities = model.Responsibilities,
                Date = model.Date,
                UserId = model.UserId,
                User = context.Users.FirstOrDefault(x => x.Id == model.UserId) ?? throw new Exception("User не существует"),
                CaseDeals = model.Cases.Select(x => new CaseDeal
                {
                    Case = context.Cases.First(y => y.Id == x.Key)
                }).ToList()
            };
        }

        public void Update(CaseAccountingDatabase context, DealBindingModel? model)
        {
            if (model == null)
            {
                return;
            }
            Subject = model.Subject;
            Responsibilities = model.Responsibilities;
            Date = DateTime.SpecifyKind(model.Date, DateTimeKind.Utc);
            if (model.Contracts.Count > 0)
            {
                Contracts = model.Contracts.Select(x => new DealContract
                {
                    Contract = context.Contracts.First(y => y.Id == x.Key)
                }).ToList();
            }
        }

        public void UpdateCases(CaseAccountingDatabase context, DealBindingModel model)
        {
            var dealCases = context.CaseDeals
                .Where(x => x.DealId == model.Id)
                .ToList();
            if (dealCases != null)
            {
                context.CaseDeals
                    .RemoveRange(dealCases
                            .Where(x => !model.Cases
                            .ContainsKey(x.CaseId))
                        );
                context.SaveChanges();
                var deal = context.Deals
                    .First(x => x.Id == Id);
                foreach (var dc in dealCases)
                {
                    model.Cases.Remove(dc.CaseId);
                }
                foreach (var dc in model.Cases)
                {
                    context.CaseDeals.Add(new CaseDeal
                    {
                        Deal = deal,
                        Case = context.Cases.First(x => x.Id == dc.Key),
                    });
                    context.SaveChanges();
                }
                _cases = null;
            }
        }

        public DealViewModel GetViewModel => new()
        {
            Id = Id,
            Subject = Subject,
            Responsibilities = Responsibilities,
            Date = Date,
            UserId = UserId
        };
    }
}
