using System;

namespace Kreta.Framework.Collections.Generic
{
    public class AssociatedEntityCollection<OwnerEntityType, CollectionEntityType> : EntityCollection<CollectionEntityType>, IAssociatedEntityCollection<CollectionEntityType>, IAssociatedEntityCollection
        where OwnerEntityType : Kreta.Framework.Entities.Entity
        where CollectionEntityType : Kreta.Framework.Entities.Entity
    {
        private IEntityCollectionDA<CollectionEntityType> m_DA = null;

        public AssociatedEntityCollection(IEntityCollectionDA<CollectionEntityType> collectionDA)
        {
            m_DA = collectionDA;
        }

        protected override void DoAdd(CollectionEntityType entity)
        {
            m_DA.AddItem(entity);
            base.DoAdd(entity);
        }

        protected override void DoRemove(CollectionEntityType entity)
        {
            m_DA.DeleteItem(entity);
            base.DoRemove(entity);
        }

        protected override void DoClear()
        {
            throw new NotSupportedException("AssociatedEntityCollection<OwnerEntityType, CollectionEntityType>.DoClear()");
        }

        public void Remove(CollectionEntityType entity)
        {
            DoRemove(entity);
        }

        public void Delete(CollectionEntityType entity)
        {
            DoRemove(entity);
        }

        public void RemoveAll()
        {
            CollectionEntityType[] tmp = new CollectionEntityType[m_Entities.Count];
            m_Entities.CopyTo(tmp);
            foreach (CollectionEntityType entity in tmp)
            {
                DoRemove(entity);
            }
        }

        public void Load()
        {
            m_DA.LoadCollection(this);
        }

        #region IAssociatedEntityCollection Members

        void IAssociatedEntityCollection.Remove(Kreta.Framework.Entities.Entity entity)
        {
            Remove((CollectionEntityType)entity);
        }

        void IAssociatedEntityCollection.Delete(Kreta.Framework.Entities.Entity entity)
        {
            Delete((CollectionEntityType)entity);
        }

        void IAssociatedEntityCollection.RemoveAll()
        {
            RemoveAll();
        }

        void IAssociatedEntityCollection.Load()
        {
            Load();
        }

        #endregion
    }
}