#!/usr/local/bin/ruby
# (c) Witold Rugowski http://nhw.pl

CITY = 'opole'
REGION = '16'

def process(ps, pages)
  current = {}
  count = 1
  while line = ps.gets
    line = line.gsub('L/','L')
    line = line.gsub('l/','l')
    line = line.gsub(/ó/,'o')
    
    if pages && line =~ /jednostek,\W+(\d+)\W+stron/
      count = $1
    end

    case line
      when /Nazwa:\W+(.*)/
        $addr.push(current) unless current.empty?
        current = {}
        current[:name] = $1
      when /Adres:\W+(.*)/
        current[:address] = $1
      when /Numer telefonu:\W+([\d\-]*)/
        current[:phone] = $1 
      when /Dni robocze:\W+([\d\-:]*)/
        current[:hours_wd] = $1
      when /Dni robocze:\W+([\d\-:]*)/
        current[:hours_wd] = $1
      when /Soboty:\W+([\d\-:]*)/
        current[:hours_sat] = $1
      when /Swieta:\W+([\d\-:]*)/
        current[:hours_hd] = $1
    end
    
  end

  $addr.push(current)
  return count
end


$addr = []

p=IO.popen("lynx --dump 'http://www.poczta-polska.pl/placowki/?miejscowosc=#{CITY}&pna1=&pna2=&ulica=&wojewodztwo=#{REGION}&powiat=&gmina=&nazwa=&OR=&ORJ=&biurofaks=0&ilosc_odpowiedzi=10'")

puts "**** First request ****"
pg_count = process(p,true).to_i

while pg_count > 1
  p=IO.popen("lynx --dump 'http://www.poczta-polska.pl/placowki/?miejscowosc=#{CITY}&page=#{pg_count}&pna1=&pna2=&ulica=&wojewodztwo=#{REGION}&powiat=&gmina=&nazwa=&OR=&ORJ=&biurofaks=0&ilosc_odpowiedzi=10'")
  puts "Page #{pg_count}"
  process(p,false)
  pg_count = pg_count -1
end

puts "W sumie #{$addr.size} placówek"

out_file = File.open("poczta_out.js","w")


out_file.write("var addr = [\n")
first_time = true
$addr.each {|i| 
  if first_time		#tak aby po ostatnim entry w tablicy nie bylo ,
    first_time = false
  else
    out_file.write(",\n")
  end
  
  out_file.write(" [\n   '"+
    i[:name].to_s+"',\n   '"+
    i[:address].to_s+"',\n   '"+
    i[:phone].to_s+"',\n   "+
    "0, 0,\n   '"+
    i[:hours_wd].to_s+"',\n   '"+
    i[:hours_sat].to_s+"',\n   '"+
    i[:hours_hd].to_s+"'\n"+
    " ]")
}

out_file.write("]\n")




