require 'net/http'
require 'timeout'
Net::HTTP.version_1_2

class InsultPlugin < Plugin
  def help(plugin, topic="")
    if(plugin == "insult")
      return "insult me|<person> => insult you or <person>"
    elsif(plugin == "msginsult")
      return "msginsult <nick> => insult <nick> via /msg"
    else
      return "insult module topics: msginsult, insult"
    end
  end
  def privmsg(m)
    suffix=""
    unless(m.params)
      m.reply "incorrect usage: " + help(m.plugin)
      return
    end
    if(m.plugin =~ /^msginsult$/)
      prefix = "you are "
      msgto = m.params
      suffix = " (from #{m.sourcenick})"
    elsif(m.params =~ /^me$/)
      prefix = "you are "
    else
      prefix = "#{m.params} is "
    end

    if(ENV['http_proxy'])
      if(ENV['http_proxy'] =~ /^http:\/\/(.+):(\d+)$/)
        proxy_host = $1
        proxy_port = $2
      end
    end

    Thread.new do
      begin
        timeout(8) {
          http = Net::HTTP.new("insulthost.colorado.edu", 1695, proxy_host, proxy_port)
          http.start {|http|
            resp = http.request_get("/")
          }
        }
      rescue TimeoutError => e
        m.reply "the insult server is unreachable (timeout) :("
        return
      end

      if resp.body.empty?
        m.reply "the insult server is unreachable :("
        return
      end

      resp.body.each_line {|l|
        if(l =~ /^You are (.*)$/)
          insult = $1
          if(m.plugin =~ /^msginsult$/)
            @bot.say msgto, prefix + insult + suffix
            m.reply "okay, I told #{msgto}: you are #{insult}"
          else
            m.reply prefix + insult + suffix
          end
          return
        end
      }

      m.reply "the insult server is unreachable :("
    end
  end
end
plugin = InsultPlugin.new
plugin.register("insult")
plugin.register("msginsult")

