#!/usr/bin/env ruby

require 'active_support'
require 'active_support/core_ext'
require 'thor'

module ActionSubscriber
  class CLI < ::Thor
    class_option :allow_low_priority_methods, :type => :boolean, :desc => "subscribe to low priority queues in addition to the normal queues", :default => false
    class_option :app, :default => "./config/environment.rb"
    class_option :mode
    class_option :host
    class_option :hosts
    class_option :prefetch, :type => :numeric, :desc => "how many messages to hold in the local queue in subscribe mode"
    class_option :pop_interval, :type => :numeric, :desc => "how long to wait between asking for messages (in milliseconds)"
    class_option :port, :type => :numeric
    class_option :threadpool_size, :type => :numeric
    class_option :times_to_pop, :type => :numeric, :desc => "how many messages to get from each queue each time we ask rabbit"

    desc "start", "Start the action subscriber subscription server"
    long_desc <<-BABOUDESC.strip_heredoc
      Action Subscriber contains a simple subscriber server to manage event subscriptions in a separate process.
    BABOUDESC

    def start
      require options[:app]

      $0 = "Action Subscriber server #{object_id}"
      puts "Loading configuration..."

      ::ActionSubscriber::Configuration.configure_from_yaml_and_cli(options)
      puts "Starting server..."

      case ::ActionSubscriber.configuration.mode
      when /pop/i then
        ::ActionSubscriber::Babou.auto_pop!
      when /subscribe/i then
        ::ActionSubscriber::Babou.start_subscribers
      end
    end
  end

  if ::RUBY_PLATFORM == "java"
    at_exit do
      ::ActionSubscriber::Babou.stop_server!
    end
  else
    [:INT, :QUIT, :TERM].each do |signal|
      trap(signal) do
        ::ActionSubscriber::Babou.stop_server!
        exit 0
      end
    end
  end
end

trap(:TTIN) {
  ::ActionSubscriber.print_subscriptions
}

trap(:USR2) {
  puts <<-CONFIG.strip_heredoc
  Action Subscriber Stats
    Pool Size: #{ ::ActionSubscriber.config.threadpool_size }
    Ready Size: #{ ::ActionSubscriber::Threadpool.ready_size }
  CONFIG
}

::ActionSubscriber::CLI.start(ARGV)
