#!/usr/bin/env ruby
# -*- ruby -*-

require 'rubygems'
require 'password'
require 'tweetstream'
require 'drb'
require "optparse"
require "ostruct"

class Rabbiter
  def initialize(options)
    @options = options
    @rabbit = DRb::DRbObject.new_with_uri(@options.rabbit_uri)
    @tweet = nil
  end

  def start
    @tweet = TweetStream::Daemon.new(@options.username,
                                     @options.password,
                                     "rabbiter")
    @tweet.track(@options.keyword) do |status|
      begin
        comment = "#{status.user.screen_name}: #{clean_text(status.text)}"
        @rabbit.append_comment(comment)
      rescue DRb::DRbConnError
        puts "Rabbiter: #{$!.class}: #{$!.message}"
      end
    end
  end

  def stop
    if @tweet
      @tweet.stop
    end
  end

  private
  def clean_text(text)
    remove_ustream_link(remove_hash_tag(text))
  end

  def remove_hash_tag(text)
    text.gsub(/\##{Regexp.escape(@options.keyword)}/, "")
  end

  def remove_ustream_link(text)
    text.gsub(/\(.* live at http:\/\/ustre\.am\/.*\)/, "")
  end
end

options = OpenStruct.new
options.keyword = 'ruby'
options.rabbit_uri = 'druby://localhost:10101'
options.username = ENV['USER'] || ENV['USERNAME']
options.password = ''

parser = OptionParser.new do |opts|
  opts.on("--keyword=KEYWROD",
          "Keyword for search Twitter",
          "(#{options.keyword})") do |keyword|
    options.keyword = keyword
  end

  opts.on("--rabbit-uri=URI",
          "Rabbit's dRuby URI",
          "(#{options.rabbit_uri})") do |uri|
    options.rabbit_uri = uri
  end

  opts.on("--username=USERNAME",
          "Username for Twitter",
          "(#{options.username})") do |username|
    options.username = username
  end

  opts.on("--password=PASSWORD",
          "User password for Twitter",
          "(#{options.password})") do |password|
    options.password = password
  end
end

parser.parse!(ARGV)

if options.password.empty?
  options.password = Password.get("Password for #{options.username}: ")
end

rabbiter = Rabbiter.new(options)

Signal.trap("INT") do
  rabbiter.stop
end

rabbiter.start
