
require 'rubygems'
require 'open-uri'
require 'hpricot'
require 'json'

=begin
csv_file = 'ID,PLANTNAME,ALIAS,COUNTY,ONLINE_MW,PEAKER,PEAKER_TYPE,FACILITY,GENERAL_FUEL,PRIMARY_FUEL,TECHNOLOGY,FUEL_SOURCE,STATUS,COGEN,TURBINE_UNIT,TURBIN_COUNT,TURBINE_MW,DATE_ONLINE,YEAR_ONLINE,DATE_BUILT,SERVICE_AREA,PLANT_CITY,OPERATOR,OWNER,OWNER_ABBR
G0004,939 COAST MANAGEMENT,,SAN DIEGO,0.230000,NO,,OIL/GAS,OIL/GAS,NATURAL GAS,RECIPROCATING ENGINE,,OPERATIONAL,COGEN,,1,,1/30/87,1987,,SDG&E,LA JOLLA,,"ONSITE ENERGY, CORP.",
H0570,A.G. WISHON,,MADERA,20.000000,NO,,HYDROELECTRIC,HYDRO,HYDRO,"HYDRO,WATER",,OPERATIONAL,NOT COGEN,GEN 1-4,4,#1 - #4 = /3.2,9/1/10,1910,1/1/10,PG&E,NORTH FORK,,PACIFIC GAS AND ELECTRIC COMPANY,PG&E
G0006,AES PLACERITA,AES PLACERITA INC.,LOS ANGELES,122.410000,NO,,OIL/GAS,OIL/GAS,NATURAL GAS,COMBINED CYCLE,,OPERATIONAL,COGEN,,3,"1=48, 2=48, 3=25",1/1/88,1988,,SCE,PLACERITA CYN.,AES PLACERITA,AES PLACERITA,AESP'
=end

csv_file = File.open("./POWER_PLANTS.txt").read
#p csv_file
lines = csv_file.split("\r")
j = 0
keys = lines[0].split("\t")
plant_text = lines[1..lines.length]
plant_list = []
plant_text.map do |plant|
  plant = plant.split("\t")
  i = 0
  hash = {}
  plant.each do |element|
    hash[keys[i]] = element
    i = i + 1
  end
  p hash["PLANT_CITY"] + ".  This is plant # " + j.to_s
  j = j+1
  geocode = Hpricot(open(URI.escape("http://maps.google.com/maps/geo?output=xml&q='#{hash["PLANT_CITY"]}, California, USA'")))
  if (geocode.at("coordinates").nil?) then 
	sleep 20
	p "No geocode, reattempting"
  	geocode = Hpricot(open(URI.escape("http://maps.google.com/maps/geo?output=xml&q='#{hash["PLANT_CITY"]}, California, USA'")))
  end    
  if (!geocode.at("coordinates").nil?) then
  sleep 0.5
  coord = geocode.at("coordinates").inner_html[0...-2].split(',')
  hash["lng"]= coord[0]
  hash["lat"] = coord[1]
  else
  p "Geocoding failed"
  hash["lng"]= 0
  hash["lat"]= 0
  end
  plant_list = plant_list + [hash]
end

json = plant_list.to_json
json = "var plants = "+ json + ';'
out = File.new("./plants.js","w")
out.write(json)
