// ========================================================================
//
// Copyright (C) 2019-2020 MARC CHEVALDONNE
//                         marc.chevaldonne.free.fr
//
// Module        : LitEntity.cs
// Author        : Marc Chevaldonné
// Last Modified : 2019-12-25
//
// ========================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace ex_042_012_EF_CF_Dictionary
{
    [Table("Lits")]
    public class LitEntity : ILit
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid UniqueId
        {
            get; set;
        }

        public string Propriétaire
        {
            get; set;
        }

        /// <summary>
        /// remplace le dictionnaire : on utilise une collection de Scores afin d'établir une relation one to many entre 
        /// LitEx et Score
        /// </summary>
        internal virtual ICollection<Score> mScores
        {
            get;
            set;
        } = new List<Score>();

        public int this[INounours nounours]
        {
            get
            {
                var score = mScores.SingleOrDefault(sc => sc.Key.Equals(nounours));
                return score != null ? score.Value : 0;
            }
            set
            {
                var score = mScores.SingleOrDefault(sc => sc.Key.Equals(nounours));
                if (score != null)
                {
                    score.Value = value;
                }
                else
                {
                    var n = nounours as Nounours;
                    if (n == null) throw new InvalidCastException("nounours should be of type Nounours");

                    Score newScore = new Score()
                    {
                        Key = n,
                        Value = value,
                        Lit = this
                    };
                    mScores.Add(newScore);
                }
            }
        }

        public ReadOnlyDictionary<INounours, int> Scores =>
            new ReadOnlyDictionary<INounours, int>(mScores.ToDictionary(kvp => kvp.Key as INounours, kvp => kvp.Value));
    }
}
