﻿#if DNX46 || NET462 || DNX451 || NET45
using System.Collections;
using System.Security.Principal;
using System.ServiceModel;

namespace Core.Components.Context
{
    /// <summary>
    /// This class allows attaching a dictionnary to a Wcf execution context.
    /// </summary>
    public class WcfContext : IExtension<OperationContext>
    {
        /// <summary>
        /// Attaches the specified owner.
        /// </summary>
        /// <param name="owner">The owner.</param>
        public void Attach(OperationContext owner) { }

        /// <summary>
        /// Detaches the specified owner.
        /// </summary>
        /// <param name="owner">The owner.</param>
        public void Detach(OperationContext owner) { }
        
        private readonly IDictionary _items;

        /// <summary>
        /// Gets the user.
        /// </summary>
        /// <value>
        /// The user.
        /// </value>
        public static IPrincipal User { get { return OperationContext.Current.ClaimsPrincipal; } }

        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <value>
        /// The items.
        /// </value>
        public static IDictionary Items
        {
            get
            {
                var context = OperationContext.Current;
                var extension = context.Extensions.Find<WcfContext>();
                if (extension == null)
                {
                    extension = new WcfContext();
                    context.Extensions.Add(extension);
                }

                return extension._items;
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is active.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is active; otherwise, <c>false</c>.
        /// </value>
        public static bool IsActive { get { return OperationContext.Current != null; } }

        /// <summary>
        /// Initializes a new instance of the <see cref="WcfContext"/> class.
        /// </summary>
        public WcfContext()
        {
            _items = new Hashtable();
        }
    }
}
#endif