#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../lib/amqp_utils/command'

class PopCommand < AmqpUtils::Command
  def prepare_options(options)
    options.banner %Q{
    |Pops a single message from the queue.
    |
    |   #{command_name} <queue>
    }.margin
  end

  def validate
    raise "need a queue name" unless args[0] && !args[0].empty?
  end

  def execute
    @queue = args[0]

    mq = MQ.new
    mq.queue(@queue).pop do |header, message|
      if message
        puts "(#{@queue})"
        puts "  Header: "
        header.properties.each do |key, value|
          puts "    #{key.inspect} => #{value.inspect}"
        end
        puts "  Message: #{message.inspect}"
      else
        puts "(#{@queue}) empty"
      end

      AMQP.stop { EM.stop }
    end
  end
end

PopCommand.run
