#!/usr/bin/perl

# simple script to grab the weather for a txt file full of locations and output the weather to each of those files. Creates /tmp/weathercache to hold the cache
#
# See Weather::Cached on cpan.org for info on how to register an account with weather.com to get a partner_id and license number

use Data::Dumper;
use Weather::Cached; 
  
mkdir '/tmp/weathercache' unless(-d "/tmp/weathercache");
  # define parameters for weather search
  my %params = (
                'cache'      => '/tmp/weathercache',
                'current'    => 1,
                'forecast'   => 0,
                'links'      => 1,
                'units'      => 's',
                'proxy'      => 'none',
                'timeout'    => 250,
                'debug'      => 0,
                'partner_id' => '0000000000',
                'license'    => '0000aaaa1111bbbb',
  );

open CITIES, "weather.txt" or die "Can't open weather.txt: $!";
@cities = <CITIES>;
close CITIES;

foreach $city (@cities)
{
   next if($city =~ /^\s*$/);
   $weather = grab_weather($city);
   output_weather($weather);
}

sub grab_weather
{
   my $city = shift;
# instantiate a new weather.com object
   my $cached_weather = Weather::Cached->new(%params);

# search for locations called 'Heidelberg'
   my $locations = $cached_weather->search($city)
      or die "No location found!\n";

# and then get the weather for each location found
   foreach (keys %{$locations}) {
      my $weather = $cached_weather->get_weather($_);
      return $weather;
   }
}

sub output_weather
{
  my $weather = shift;

# print Dumper($weather);

  open OUTPUT, "> weather-$weather->{loc}{dnam}.html" or die "Can't open weather-$weather->{loc}{dnam}.html $!";

  print OUTPUT "<p><b>Current Weather:</b>\n";
  print OUTPUT "<br /><a href=\"http://www.w3.weather.com/outlook/travel/local/$weather->{loc}{id}\" target=\"_blank\"><img src=\"http://image.weather.com/web/common/wxicons/31/$weather->{cc}{icon}.gif\" border=0 align=left> $weather->{cc}{t} $weather->{cc}{tmp}$weather->{head}{ut}, $weather->{cc}{hmid}\% humidity, wind $weather->{cc}{wind}{t} $weather->{cc}{wind}{s}$weather->{head}{us}</a>";
  close OUTPUT;
}
