#!/usr/bin/env ruby

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

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.
    |
    |Peek options:
    }.margin
    options.opt :format, 'The format that the messages should be displayed as',
      :short => :none, :default => 'pretty'
  end

  def validate
    Trollop::die "need a queue name" unless args[0] && !args[0].empty?

    @formatter = AmqpUtils::MessageFormatter.for_type(options[:format])
    Trollop::die :format, "not an available type: #{AmqpUtils::MessageFormatter.types.join(", ")}" unless @formatter
  end

  def execute
    @queue = args[0]

    mq = MQ.new
    mq.queue(@queue, :passive => true).pop(:ack => true) do |header, message|
      if message
        puts "(#{@queue})"
        @formatter.generate(STDOUT, header, message)
      else
        puts "(#{@queue}) empty"
      end

      AMQP.stop { EM.stop }
    end
  end
end

PeekCommand.run
