#! /usr/pkg/bin/ruby34
# -*- ruby -*-
#
# Copyright (C) 2010-2012  Kouhei Sutou <kou@cozmixng.org>
# Copyright (C) 2010       OBATA Akio <obata@lins.jp>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

require "drb/drb"

require "rabbit/console"
require "rabbiter"

include Rabbiter::GetText

def parse(args=ARGV, logger=nil)
  Rabbit::Console.parse!(args, logger) do |parser, options|
    options.version = Rabbiter::VERSION
    options.rabbit_uri = options.druby_uri
    options.filters = []
    options.user_languages = []
    options.log_status = false

    parser.separator ""

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

    parser.on("--filter=FILTER",
              _("Filter by word."),
              _("To use multiple filters, use this option multiple.")) do |filter|
      options.filters << filter
    end

    parser.on("--user-language=LANGUAGE",
              _("Filter by user language."),
              _("(e.g.: ja, en)"),
              _("To use multiple language, use this option multiple.")) do |language|
      options.user_languages << language
    end

    parser.category(_("Debug"))

    parser.on("--[no-]log-status",
              _("Log target statuses.")) do |boolean|
      options.log_status = boolean
    end
  end
end

def target?(status, options)
  return true if options.user_languages.empty?
  user = status["user"]
  return false if user.nil?
  user_lang = user["lang"]
  return false if user_lang.nil?
  options.user_languages.include?(user_lang)
end

def clean_text(text, filters)
  remove_ustream_link(remove_hash_tag(text, filters))
end

def remove_hash_tag(text, filters)
  hash_tag_regexps = filters.collect do |filter|
    if filter.start_with?("#")
      Regexp.escape(filter)
    else
      Regexp.escape("\##{filter}")
    end
  end
  text.gsub(Regexp.union(*hash_tag_regexps), "")
end

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

def main
  options, logger = parse
  if options.filters.empty?
    logger.error(_("must specify one or more filters by --filter"))
    exit(false)
  end

  rabbit = DRbObject.new_with_uri(options.rabbit_uri)
  client = Rabbiter::Client.new(logger)
  client.start(*options.filters) do |status|
    text = status["text"]
    next if text.nil?
    next unless target?(status, options)
    text = clean_text(status['text'], options.filters)
    comment = "@#{status['user']['screen_name']}: #{text}"
    logger.info(comment)
    begin
      rabbit.append_comment(comment)
    rescue DRb::DRbConnError
      logger.error("Rabbiter: #{$!.class}: #{$!.message}")
    end
  end

  main_loop = GLib::MainLoop.new
  trap("INT") do
    client.close
    main_loop.quit
  end
  main_loop.run
end

main
