require 'rexml/document'

class SlashdotPlugin < Plugin
  include REXML
  def help(plugin, topic="")
    "slashdot search <string> [<max>=4] => search slashdot for <string>, slashdot [<max>=4] => return up to <max> slashdot headlines"
  end
  def privmsg(m)
    if m.params && m.params =~ /^search\s+(.*)\s+(\d+)$/
      search = $1
      limit = $2.to_i
      search_slashdot m, search, limit
    elsif m.params && m.params =~ /^search\s+(.*)$/
      search = $1
      search_slashdot m, search
    elsif m.params && m.params =~ /^(\d+)$/
      limit = $1.to_i
      limit = 6 if limit > 6
      slashdot m, limit
    else
      slashdot m
    end
  end
  
  def search_slashdot(m, search, max=4)
    begin
      xml = Utils.http_get("http://slashdot.org/search.pl?content_type=rss&query=#{search}")
    rescue URI::InvalidURIError, URI::BadURIError => e
      m.reply "illegal search string #{search}"
      return
    end
    unless xml
      m.reply "search for #{search} failed"
      return
    end
    doc = Document.new xml
    unless doc
      m.reply "search for #{search} failed"
      return
    end
    done = 0
    doc.elements.each("*/item") {|e|
      reply = sprintf("%32s / %s", e.elements["title"].text[0,32], e.elements["link"].text)
      m.reply reply
      done += 1
      break if done >= max
    }
  end
  
  def slashdot(m, max=4)
    xml = Utils.http_get("http://slashdot.org/slashdot.xml")
    unless xml
      m.reply "slashdot news parse failed"
      return
    end
    doc = Document.new xml
    unless doc
      m.reply "slashdot news parse failed"
      return
    end
    done = 0
    doc.elements.each("*/story") {|e|
      reply = sprintf("%32s / %10s / %8s", e.elements["title"].text[0,32],
                      e.elements["author"].text, e.elements["time"].text)
      m.reply reply
      done += 1
      break if done >= max
    }
  end
end
plugin = SlashdotPlugin.new
plugin.register("slashdot")
