#!/usr/bin/env ruby

lib_dir = File.join(File.dirname(__FILE__), '..', 'lib')
$LOAD_PATH.unshift lib_dir if File.directory?(lib_dir)

require 'messenger'
require 'trollop'
require 'yaml'


#-------------------------------------
# Support
#-------------------------------------

class Hash

  def symbolize_keys
    inject({}) do |options, (key, value)|
      options[(key.to_sym rescue key) || key] = value
      options
    end
  end

  def symbolize_keys!
    self.replace(self.symbolize_keys)
  end

end


#
# Configure options
#

if File.exists?(File.expand_path("~/.messenger"))
  options = YAML.load_file(File.expand_path("~/.messenger")).symbolize_keys!
else
  options = {}
end

trollop_options = Trollop::options do
  version "Messenger #{Messenger::VERSION} (c) Zencoder Inc. All rights reserved, etc."
  banner <<-EOS
Messenger makes sending messages easy.

Usage:
        messenger [options] <service> <message>

Where [options] are:
EOS

  # Global options
  opt :timeout, "The number of seconds to allow for the call", :type => Integer

  # Email options
  opt :email_from, "Who the message is from (email).", :type => String
  opt :email_subject, "The message subject (email).", :type => String

  # Jabber options
  opt :jabber_id, "The jabber ID to connect as (user@example.com)", :type => String
  opt :jabber_password, "The password for your jabber id", :type => String

  # Notifo options
  opt :notifo_api_username, "The service's API username", :type => String
  opt :notifo_api_secret, "The service's API secret", :type => String
  opt :notifo_title, "The notificaiton title", :type => String
  opt :notifo_url, "Open this URL", :type => String

  # CLI options
  # opt :silent, "Don't print anything to stdout", :default => false
  # opt :verbose, "Print verbose output on success", :default => false
end

options.merge!(trollop_options.reject{|k,v| v.nil?})

#
# Validate input
#

if ARGV[0].nil? || ARGV[1].nil?
  puts <<-EOS
Error: no service or message specified.

Usage (--help for more):

        messenger [options] <service> <message>

EOS
  exit -1
end


#
# Run Messenger
#
puts "# Sending message to #{ARGV[0]}"
begin
  result = Messenger.deliver(ARGV[0], ARGV[1], options)
  if result.success?
    puts "# Message sent successfully"
  else
    puts "# Message not sent"
    puts "# Details:"
    puts result.response
  end
rescue => e
  puts "# **Error** #{e}"
  puts e.backtrace
end