//.################################################
//# 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;

namespace TestApplicationDomainModel.TestAssociations
{
    [Serializable]
    [ObjectInstance(Name = "Bi-Directional Many-to-Many")]
    internal class BiDir_ManyToMany
    {
        private ObjectList<EntityBase> _Many = new ObjectList<EntityBase>();

        public BiDir_ManyToMany()
        {
            _Many.Changing += new NotifyListChangesEventHandler<EntityBase>(_Many_Changing);
            _Many.Changed += new NotifyListChangesEventHandler<EntityBase>(_Many_Changed);
        }

        public Guid ID { get; internal set; }

        /// <summary>
        /// It should be possible to replace this collection with a different one
        /// </summary>
        public ObjectList<EntityBase> NormalMany
        {
            get { return _Many; }
            set { _Many = value; }
        }


        /// <summary>
        /// It should be possible to add/remove items from this
        /// </summary>
        public ObjectList<EntityBase> ReadOnlyMany
        {
            get { return _Many; }
        }


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

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

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

                case NotifyCollectionChangedAction.Remove:
                    break;
            }
        }

    }
}
