require 'net/http'
require 'uri/common'
require "rexml/document"

Net::HTTP.version_1_2

class GDPlugin < Plugin
  include REXML
  def help(plugin, topic="")
    "gd <person> => search gd.db.com for <person> (exact match), gdfull <person> => same as gd, but more info returned, gdsmart <person> => smart gd search for <person>"
  end
  def privmsg(m)
    orig = m.params.dup
    searchfor = URI.escape m.params

    if(m.plugin == "gdsmart")
      searchtype = "smartsearch"
    else
      searchtype = "person"
    end
    query = "/perl/servlet/GdSearch?searchtype=#{searchtype}&uid=#{searchfor}"
    query += "&visualtype=xml"

    result = "not found!"

    proxy_host = nil
    proxy_port = nil

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

    http = Net::HTTP.new("gd.db.com", 80, proxy_host, proxy_port)

    http.start {|http|
      resp = http.get(query)
      if resp.code == "200"
        matches = Array.new
        doc = Document.new resp.body
        doc.elements.each("RESULTSLIST/RESULTROW") { |e|
          person = Hash.new
          person["name"] = e.attributes["uid"]
          person["email"] = e.attributes["email"]
          person["phone"] = e.attributes["telno"]
          person["division"] = e.attributes["division"]
          person["loc"] = e.attributes["citycountry"]
          person["dirid"] = e.attributes["dbdirid"]
          matches << person
        }
        msg1 = doc.elements["RESULTSLIST/MESSAGE1"].attributes["CONTENT"]
        if(msg1 =~ /^Showing records 1 - 10 of (\d+)$/)
          result = "#$1 matches, can you be more specific?"
        elsif(matches.length > 1)
          result = "#{matches.length} matches: "
          list = ""
          matches.each {|mat|
            list += ", " if(list.length > 0)
            list += "#{mat['name']} (#{mat['division']})"
          }
          result += list
        elsif(matches.length == 1)
          p = matches[0]
          if(m.plugin == "gdfull")
            result = "#{p['name']} (#{p['division']}): #{p['phone']}, #{p['email']}, #{p['loc']}"
          else
            result = "#{p['name']} (#{p['division']}): #{p['phone']}"
          end
        else
          result = "#{orig}: not found"
        end
      end
    }
    m.reply result
  end
end
plugin = GDPlugin.new
plugin.register("gd")
plugin.register("gdfull")
plugin.register("gdsmart")
