﻿using System;
using Arch.Client.Contract;
using EasyNetQ;
using Nancy;

namespace Arch.Client.Bridge
{
    public class BridgeModule : NancyModule
    {
        public BridgeModule(IBus bus)
        {
            var messageTypes = ContractMessageResolver.GetMessageTypes();

            foreach (var messageType in messageTypes)
            {
                var route = string.Format("/in/{0}", messageType.Name);

                ConfigureRoute(bus, route, messageType);
            }
        }

        private void ConfigureRoute(IBus bus, string route, Type messageType)
        {
            Post[route] = _ =>
            {
                var message = this.Bind(messageType);
                bus.Publish(messageType, message);
                return HttpStatusCode.OK;
            };
        }
    }
}