require 'net/telnet'

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
    
    begin
      host = Net::Telnet::new({
        "Host"       => "insulthost.colorado.edu",
        "Timeout"    => 3,
        "Port"       => 1695
      })
      if(host)
        line = host.waitfor(/^You are /)
        if(line)
          line.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
          }
        else
          m.reply "the insult server is unreachable :("
          return
        end
      else
        m.reply "the insult server is unreachable :("
        return
      end
    rescue TimeoutError
      m.reply "the insult server is unreachable (timeout) :("
      return
    end
  end
end
plugin = InsultPlugin.new
plugin.register("insult")
plugin.register("msginsult")
