﻿namespace CC.Cumps.Configuration
{
    using Bus;
    using MassTransit;
    using MassTransit.Log4NetIntegration;
    using NEventStore.Dispatcher;
    using StructureMap;
    using StructureMap.Configuration.DSL;

    public class BusRegistry : Registry
    {
        public BusRegistry()
        {
            For<IServiceBus>().Singleton().Use(CreateServiceBus);
            For<IBus>().Singleton().Use(CreateBus);

            //Forward<IBus, IDispatchCommits>(); // This is problematic, as Forward registers IDispatchCommits as Transient instead of Singleton, causing a NestedContainer to dispose it
            For<IDispatchCommits>().Singleton().Add(x => (object)x.GetInstance<IBus>() as IDispatchCommits);
        }

        private static IServiceBus CreateServiceBus()
        {
            var bus = ServiceBusFactory.New(b =>
            {
                b.SetConcurrentConsumerLimit(1);
                b.UseLog4Net();
                
                b.DisablePerformanceCounters();
                //b.UseMsmq(x => x.VerifyMsmqConfiguration());
                //b.ReceiveFrom("msmq://localhost/test");
                b.ReceiveFrom("loopback://localhost/queue");

                b.Subscribe(x => x.LoadFrom(ObjectFactory.Container));
            });

            return bus;
        }

        private static IBus CreateBus(IContext context)
        {
            return new MassTransitPublisher(context.GetInstance<IServiceBus>());
        }
    }
}