//.################################################
//# Copyright © 2006-2010 Evolving Software Ltd   #
//# Author: Vijay Patel                           #
//################################################'

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;

using Evolving.DomainTypes;
using Evolving.TrueView.Domain.Attributes;
using System.Diagnostics;
using System.Collections.Generic;

namespace TestApplicationDomainModel.TestAssociations
{
    [Serializable]
    [ObjectInstance(Name = "Bi-Directional One-to-Many")]
    internal class BiDir_OneToMany : EntityBase
    {

        private ObjectList<object> _OneToMany;

        public BiDir_OneToMany()
        {
            _OneToMany = new ObjectList<object>();
            _OneToMany.Changing += new NotifyListChangesEventHandler<object>(readonlyMany_Changing);
            _OneToMany.Changed += new NotifyListChangesEventHandler<object>(readonlyMany_Changed);
            this.ReadOnlyMany = _OneToMany;
        }

        public Guid ID { get; internal set; }

        /// <summary>
        /// It should be possible to add/remove items from this
        /// </summary>
        public IEnumerable<object> ReadOnlyMany { get; private set; }


        void readonlyMany_Changing(object sender, IListChangeEventArgs<object> e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Replace:
                    if (_OneToMany.Contains(e.Item))
                    {
                        Trace.TraceWarning(string.Concat(e.Item, " already belongs to ", this));
                        e.IsCancelled = true;
                    }
                    break;

                case NotifyCollectionChangedAction.Remove:
                    if (!_OneToMany.Contains(e.Item))
                    {
                        e.IsCancelled = true;
                    }
                    break;
            }
        }

        void readonlyMany_Changed(object sender, IListChangeEventArgs<object> e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Replace:
                    break;

                case NotifyCollectionChangedAction.Remove:
                    break;
            }
        }
    }
}
