#!/usr/bin/env ruby

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

class EnqueueCommand < AmqpUtils::Command
  def prepare_options(options)
    options.banner %Q{
    |Publishes a message to a particular queue.
    |
    |  #{command_name} <queue> <message>
    |
    |Enqueue options:
    }.margin
    options.opt :persistent, 'Mark messages as persistent.', :short => :none
    options.opt :count, 'Number of times the message should be published.', :type => :int, :default => 1
  end

  def validate
    raise "need a queue to publish to" unless args[0] && !args[0].empty?
    raise "need a message to publish" unless args[1] && !args[1].empty?
  end

  def execute
    @queue, @message = args

    publisher = EM.spawn do |queue, message, messages, options|
      @progress ||= Clio::Progressbar.new('Enqueuing', options[:count])

      if messages > 0
        @mq ||= MQ.new
        @mq.queue(queue, :durable => true, :auto_delete => false).
          publish(message, :persistent => options.persistent)

        @progress.inc
        publisher.notify(queue, message, messages - 1, options)
      else
        @progress.finish
        EM.next_tick { AMQP.stop { EM.stop } }
      end
    end

    publisher.notify(@queue, @message, options[:count], options)
  end
end

EnqueueCommand.run
