namespace Caliburn.Micro.Core {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    /// 
    /// A base class for various implementations of .
    /// 
    /// The type that is being conducted.
    public abstract class ConductorBase : Screen, IConductor, IParent where T : class {
        ICloseStrategy closeStrategy;
        /// 
        /// Gets or sets the close strategy.
        /// 
        /// The close strategy.
        public ICloseStrategy CloseStrategy {
            get { return closeStrategy ?? (closeStrategy = new DefaultCloseStrategy()); }
            set { closeStrategy = value; }
        }
        void IConductor.ActivateItem(object item) {
            ActivateItem((T) item);
        }
        void IConductor.DeactivateItem(object item, bool close) {
            DeactivateItem((T) item, close);
        }
        IEnumerable IParent.GetChildren() {
            return GetChildren();
        }
        /// 
        /// Occurs when an activation request is processed.
        /// 
        public virtual event EventHandler ActivationProcessed = delegate { };
        /// 
        /// Gets the children.
        /// 
        /// The collection of children.
        public abstract IEnumerable GetChildren();
        /// 
        /// Activates the specified item.
        /// 
        /// The item to activate.
        public abstract void ActivateItem(T item);
        /// 
        /// Deactivates the specified item.
        /// 
        /// The item to close.
        /// Indicates whether or not to close the item after deactivating it.
        public abstract void DeactivateItem(T item, bool close);
        /// 
        /// Called by a subclass when an activation needs processing.
        /// 
        /// The item on which activation was attempted.
        /// if set to true activation was successful.
        protected virtual void OnActivationProcessed(T item, bool success) {
            if (item == null) {
                return;
            }
            var handler = ActivationProcessed;
            if (handler != null) {
                handler(this, new ActivationProcessedEventArgs
                {
                    Item = item,
                    Success = success
                });
            }
        }
        /// 
        /// Ensures that an item is ready to be activated.
        /// 
        /// The item that is about to be activated.
        /// The item to be activated.
        protected virtual T EnsureItem(T newItem) {
            var node = newItem as IChild;
            if (node != null && node.Parent != this)
                node.Parent = this;
            return newItem;
        }
    }
}