#!/usr/bin/env ruby

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

class PeekCommand < AmqpUtils::Command
  def prepare_options(options)
    options.banner %Q{
    |Displays the head of the queue without removing the message from the queue.
    |
    |  #{command_name} <queue>
    |
    |  NOTE: This operation does have side effects on the server. The message is
    |        placed at the end of the queue after returning from this method. The
    |        message is also marked as being redelivered.
    }.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(:ack => true) 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

PeekCommand.run
