#!/usr/bin/ruby

require 'acpc_dealer'
require 'acpc_table_manager'
require 'redis'
require 'json'
require 'optparse'
require 'yaml'

ARGV << '-h' if ARGV.empty?

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: #{$PROGRAM_NAME} [options]"
  
  opts.version = AcpcTableManager::VERSION

  opts.on_tail('-h', '--help', 'Show this message') do
    puts opts
    exit
  end

  opts.on('-t', '--table_manager TABLE MANAGER CONFIG', 'Table manager configuration file.') do |c|
    options[:table_manager_config] = File.expand_path c, Dir.pwd
  end
end.parse!

raise OptionParser::MissingArgument, 'TABLE MANAGER CONFIG' unless options[:table_manager_config]

raise OptionParser::ArgumentError, "#{options[:table_manager_config]} doesn't exist." unless File.exist?(options[:table_manager_config])

CONFIG_FILE = options[:table_manager_config]

AcpcTableManager.load! CONFIG_FILE

Signal.trap('INT') { exit }
Signal.trap('TERM') { exit }

communicator = AcpcTableManager::TableManagerReceiver.new('table-manager')

AcpcTableManager.config.log(
  __method__,
  options: options,
  version: AcpcTableManager::VERSION,
  receive_channel: communicator.channel
)

loop do
  begin
    communicator.subscribe_with_timeout do |match_info|
      AcpcTableManager.config.log(__method__, match_info: match_info)

      raise "No match information provided in message, \"#{message}\" sent on channel, \"#{channel}\"." unless match_info

      AcpcTableManager.enqueue_match(
        match_info['game_def_key'],
        match_info['players'],
        match_info['random_seed']
      )
      AcpcTableManager.start_matches_if_allowed
    end
  rescue AcpcTableManager::SubscribeTimeout
    AcpcTableManager.start_matches_if_allowed
  rescue Redis::ConnectionError => e
    AcpcTableManager.config.log(
      __method__,
      {
        message: e.message,
        exit: true,
        backtrace: e.backtrace
      },
      Logger::Severity::ERROR
    )
    AcpcTableManager.notify e
    exit
  rescue => e
    AcpcTableManager.config.log(
      __method__,
      {
        message: e.message,
        backtrace: e.backtrace
      },
      Logger::Severity::ERROR
    )
    AcpcTableManager.notify e
  end
end
