package require http

bind pub -|- !eniro        rud:pub:eniro

proc rud:pub:eniro {nick uhost hand chan arg} {
  if {[string trim $arg] == "" } {
    putquick "NOTICE $nick :\00314\[\003ERROR\00314\]\003 Enter a number to search for (swedish only)"
    return
  }
  set token [http::geturl http://privatpersoner.eniro.se/query?stq=0&firstname=&lastname=&area=&phone_number=$arg&what=wphone&firstnameType=trunc&lastnameType=trunc&addressType=trunc -timeout 10000]
  upvar #0 $token state
  if {[::http::ncode $token] == "200"} {
    set data [split $state(body) "\n"]
    if { [lindex [split [string range [string trim [lindex $data 95]] 15 end-7] " "] 4] == "ingen" } {
        putserv "NOTICE $nick :No hits"
    } elseif { [string match "*Mobilnr*" [lindex $data 132]] } {
            set name [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 131]]]
            set phone [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 132]]]
            set adress [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 135]]]

            putserv "NOTICE $nick :$name"
            putserv "NOTICE $nick :$adress"
            putserv "NOTICE $nick :$phone"
    } elseif { [string match "*Gula Sidorna*" [lindex $data 51]] } {
            http::cleanup $token
            set url [string range [lindex $data 51] [expr [string first \" [lindex $data 51]]+1] [expr [string first \" [lindex $data 51] [expr [string first \" [lindex $data 51]]+1]]-1]]
            set token [http::geturl $url -timeout 10000]
            upvar #0 $token state
            set data [split $state(body) "\n"]

            set name [string range [lindex $data 377] [expr [string first > [lindex $data 377]]+1] [expr [string first < [lindex $data 377]]-1]]
            set phone [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 382]]]
            set adress [string trim [lindex $data 383]]

            putserv "NOTICE $nick :$name"
            putserv "NOTICE $nick :$adress"
            putserv "NOTICE $nick :$phone"

    } else {
            set name [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 132]]]
            set phone [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 133]]]
            set adress [string trim [string map { <b> "" </b> "" <br> "" } [lindex $data 134]]]

            putserv "NOTICE $nick :$name"
            putserv "NOTICE $nick :$adress"
            putserv "NOTICE $nick :$phone"
    }
  } else {
        putserv "NOTICE $nick :Problem connecting to server"
  }
  http::cleanup $token
}

putlog "rud-eniro.tcl loaded"