#!/usr/bin/ruby

require 'yaml'
require 'optparse'
require 'chatops_rpc'
require 'active_support/all' # Required by ChatopsController

options = {}
parser = OptionParser.new do |opts|
  opts.banner = "Usage: run.rb [options]"

  opts.on("-cCONFIG", "--config=CONFIG", "Configuration file path") do |v|
    options[:config_path] = v
  end
  opts.on("-pKEY", "--private-key=KEY", "Private key file path") do |v|
    options[:private_key_path] = v
  end

   opts.on("-h", "--help", "Prints this help") do
    puts opts
    exit
  end
end
parser.parse!

unless options[:private_key_path] && options[:config_path]
  puts "Please specify the private key (-k) and configuration paths (-c)"
  puts parser
  exit
end

configuration = HashWithIndifferentAccess.new(YAML.safe_load(File.read(options[:config_path])))
private_key = File.read(options[:private_key_path])

client = ChatopsRPC::Client.new(configuration.merge({ private_key: private_key }))
puts "!! Client setup successfully! Found #{client.clients.length} prefixs: (#{client.clients.keys.join(", ")})"
puts "!! Type one of the previous prefixs to see the available chatops."
loop do
  print "$ "
  $stdout.flush
  begin 
    command = gets
  rescue Interrupt => e
    puts "Goodbye."
    exit
  rescue SignalException => e
    puts "Goodbye."
    exit
  end
  if command == nil
    puts "Goodbye."
    exit
  end
  command.chomp!
  begin
    resp = client.chat command, configuration["user"], configuration["room"] || "123"
  rescue ChatopsRPC::Errors::NoMatchingCommandRegex => e
    possible_prefixes = client.clients.keys
    prefix = command.split(" ")[0]
    if possible_prefixes.include?(prefix)
      chatops_commands = client.clients[prefix].get_list
      puts "> Couldn't find matching command"
      puts chatops_commands["methods"].map {
        |name, metadata| "> #{prefix} #{metadata["help"]}" 
      }.join("\n")
      next
    end

    puts e.message
    next
  rescue ChatopsRPC::Errors::ChatopSeverOffline => e
    puts e.message
    next
  end

  if resp.success?
    puts "> #{resp.message}"
  else
    puts "X #{resp.message}"
  end
end