/// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (message is EventRecieved)
            {
                HandleBackgroundCompletion(context, (EventRecieved)message);
                return;
            }
            if (!(message is ReceivedMessage))
            {
                context.SendUpstream(message);
                return;
            }


            var msg  = (ReceivedMessage)message;
            var type = msg.Message.Headers["Content-Type"];

            if (type == null || type != "command/reply")
            {
                context.SendUpstream(message);
                return;
            }

            SendCommandMessage nextCommand = null;
            ICommand           curMsg;

            lock (_outbound)
            {
                if (_current == null)
                {
                    throw new InvalidOperationException("No active command set.");
                }
                _logger.Trace("Got reply for " + _current);
                curMsg      = _current;
                nextCommand = _outbound.Count > 0 ? _outbound.Dequeue() : null;
                _current    = null;
            }

            if (curMsg is BgApiCmd)
            {
                HandleBgApi(context, msg.Message, (BgApiCmd)curMsg);
            }
            else
            {
                var result = msg.Message.Headers["Reply-Text"].StartsWith("+");
                var body   = msg.Message.Headers["Reply-Text"];
                var reply  = new CommandReply(curMsg, result, body);
                _logger.Debug("Sending reply " + body);
                context.SendUpstream(reply);
            }

            if (nextCommand != null)
            {
                _logger.Trace("Sending next command down: " + nextCommand.Command);
                SendCommand(context, nextCommand);
            }
        }
        private void SendCommand(IPipelineHandlerContext context, SendCommandMessage msg)
        {
            if (msg.Command is AuthCmd || msg.Command is SubscribeOnEvents)
            {
                context.SendDownstream(msg);
                _current = msg.Command;
                return;
            }

            _current = new BgApiCmd(msg.Command);
            var message = new SendCommandMessage(_current);

            context.SendDownstream(message);
        }