# {{{ Weather
bar_applet("weather", 0) do |wmii, bar|
  require 'net/http'
  require 'time'
  ausgabe = ""
  Thread.new do
    agent = 'ruby-wmii #{WMIIRC_VERSION} (#{WMIIRC_RELEASE_DATE})'
    metar = wmii.plugin_config["ollis-plugins:weather"]["metar"] || ["eddv"]
    metar = metar.to_s
    loop do
      http = Net::HTTP.new('weather.noaa.gov', 80)
      page = http.start do
        req = Net::HTTP::Get.new('http://weather.noaa.gov/pub/data/observations/metar/decoded/'+metar.upcase+'.TXT', 'User-Agent' => agent)
        http.request(req).body
      end
      page = page.to_a
      page[0] = "Location: " + page[0].chomp
      page[1] = "Date: " + page[1].chomp
      feld = Hash.new
      feld["Wind"], feld["Relative Humidity"], feld["Sky conditions"] = '','','';
      page.each do |line|
        name, wert = line.split(/\s*:\s*/, 2)
        feld[name] = wert
      end
      temperature = feld["Temperature"].scan(/\((.+)\)/).to_s
      temperature.sub!(/ /,  '° ')
      ort = feld["Location"].scan(/(^[^)]+\))/).to_s
      date = feld["Date"].scan(/\/ ([0-9]{4})\.([0-9]{2})\.([0-9]{2}) ([0-9]{2})([0-9]{2}) UTC/)
      year, month, day, hour, minute = date[0][0..4]
      gmt_time = Time.gm(year, month, day, hour, minute, 0)
      localtime =  gmt_time.localtime
      bar.data = temperature.chomp
      ausgabe = <<EOF
Current conditions at #{ort}
Last updated #{localtime}
Wind: #{feld["Wind"].chomp}
Temperature: #{temperature}
Relative Humidity: #{feld["Relative Humidity"].chomp}
Sky conditions: #{feld["Sky conditions"].chomp}
EOF
      sleep 15*60
    end
  end
  xmessagebox = "xmessage -center -buttons quit:0 -default quit -file -"
  fl = lambda{ wmii.write "/view/ctl", "select 0" }
  toggle_fl = lambda{ sleep 2; wmii.write "/view/ctl", "select toggle" }
  bar.on_click(MOUSE_BUTTON_LEFT){ fl[]; system "echo '#{ausgabe}' | wmiisetsid #{xmessagebox} &"; toggle_fl[] }
end