using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;

using BeWo.Data;
using BeWo.Service.Core;

namespace BeWo.Service.Multitenancy
{
    public class MultitenancyContextInitializer : ICallContextInitializer
    {
        public void AfterInvoke(object pCorrelationState)
        {
            if (pCorrelationState is MultitenancyOperationContextExt)
            {
                OperationContext.Current.Extensions.Remove((MultitenancyOperationContextExt)pCorrelationState);
            }
        }

        public object BeforeInvoke(InstanceContext pInstanceContext, IClientChannel pChannel, Message pMessage)
        {
            try
            {
                int lIndex = pMessage.Headers.FindHeader("Multitenancy", "http://beyondsoft.de/Multitenancy.xsd");

                if (lIndex > -1)
                {
                    XmlReader lReader = pMessage.Headers.GetReaderAtHeader(lIndex);

                    lReader.ReadToFollowing("Tenant");
                    var lTenant = lReader.ReadString();

                    var lExt = new MultitenancyOperationContextExt { Tenant = lTenant };
                    OperationContext.Current.Extensions.Add(lExt);
                    return lExt;
                }

                return null;
            }
            catch (Exception e)
            {
                throw Utils.CreateBeWoFaultException(e);
            }
        }
    }
}