#!/usr/bin/perl
# -*- Perl -*-

#---------------------------------------------------------------------------
#  File:
#      get_weather_sp
#  Description:
#      A perl script that gets the weather forecast for Spain using INM data
#  Author:
#      Ricardo Arroyo      ricardo.arroyo@ya.com
#    adapted from get_weather_ca, written by
#      Harald Koch     chk@pobox.com
#    based extensively on get_weather, written by
#      Bruce Winter    bruce@misterhouse.net   http://misterhouse.net
#  Latest version:
#      http://misterhouse.net/mh/bin
#
#  Copyright 2002 Bruce Winter
#
#---------------------------------------------------------------------------
#

use strict;

my ($Pgm_Path, $Pgm_Name);
BEGIN {
    ($Pgm_Path, $Pgm_Name) = $0 =~ /(.*)[\\\/](.+)\.?/;
    ($Pgm_Name) = $0 =~ /([^.]+)/, $Pgm_Path = '.' unless $Pgm_Name;
}

my ($Version) = q$Revision: 420 $ =~ /: (\S+)/; # Note: revision number is auto-updated by cvs

#print "Command: $Pgm_Name @ARGV\n";
#print "Version: $Version\n";

use Getopt::Long;
my %parms;
if (!&GetOptions(\%parms, "reget", "h", "help", "v", "debug", "city:s", "zone:s", "state:s", "file=s", "no_log") or
    @ARGV or
    ($parms{h} or $parms{help})) {
    print<<eof;

$Pgm_Name gets weather info

Usage:

  $Pgm_Name [options] 

    -h         => This help text
    -help      => This help text
    -v         => verbose
    -debug     => debug

    -reget     => force HTML fetch

    -city     xxx => xxx is the code for the city you want.
    -zone     xxx => xxx is the zone name. Not used. defined to have compatibility with get_weather (us) version
    -state    xxx => xxx is the state name. not used. defined to have compatibility with get_weather (us) version
    -file     xxx => xxx is the output filename

    -no_log       => Unless this option is used, the results also get filed 
                     into the data_dir/web directory

  Example:
    $Pgm_Name -city YYZ

eof
    exit;
  }

my ($conditions, $forecast, %data);
my %config_parms;


use vars qw(%Weather @Weather_Forecast);

my $caller = caller;
my $return_flag = ($caller and $caller ne 'main') ? 1 : 0;

#use my_lib "$Pgm_Path/../lib/site"; # See note in lib/mh_perl2exe.pl for lib -> my_lib explaination
BEGIN { eval "use lib '$Pgm_Path/../lib', '$Pgm_Path/../lib/site'" } # Use BEGIN eval to keep perl2exe happy

require 'handy_utilities.pl';       # For read_mh_opts funcion
&main::read_mh_opts(\%config_parms, $Pgm_Path);

use HTML::TableExtract;
use Date::Parse;
use Date::Format;

#set madrid (Retiro) as default
$parms{city}  = $config_parms{weather_inm_city} unless $parms{city};
$parms{city}  = '08222'                         unless $parms{city};

my $WeatherURL;
my $WeatherURLdata;
$WeatherURL = 'http://www.inm.es/web/infmet/tobsr/emas.html';
$WeatherURLdata = 'http://www.inm.es/wwb/tobsr/emasdat.js';

my $f_weather_html = "$config_parms{data_dir}/../web/ia5/outside/weather_local.html";
my $f_weather_data = "$config_parms{data_dir}/weather_data";
my $f_weather_temp = "$config_parms{data_dir}/weather_temp";

my $debug = 1 if ($parms{debug});

###############
# get weather #
###############

    get_url_ua($WeatherURL, $f_weather_html);
    my $html = &file_read($f_weather_html);
    $html =~ s|<html>|<html>\n<BASE href='http://www.inm.es/web/infmet/tobsr/'>|i;
#    print "HTML:\n$html\n" if $debug;
    &file_write($f_weather_html, $html);

#################
# parse weather #
#################

    get_url_ua($WeatherURLdata, $f_weather_temp);
    print "parsing weather data from $f_weather_html\n" if $parms{v};
    &parse_weather_sp($f_weather_temp);

################
# save weather #
################

print "saving weather data to $f_weather_data\n" if $parms{v};
&save_weather_sp($f_weather_data);

exit(0);

###############
# subroutines #
###############

# from get_url
sub get_url_ua {
    my $url = shift;
    my $file = shift;

    use LWP::UserAgent;

    my $ua = new LWP::UserAgent;
    $config_parms{proxy} = $ENV{HTTP_PROXY}           unless $config_parms{proxy};
    $ua -> proxy(['http', 'ftp'] => $config_parms{proxy}) if $config_parms{proxy};

    $ua->timeout([120]);         # Time out after 60 seconds 
    $ua->env_proxy(); 

    my $request = new HTTP::Request('GET', $url);
    my $response;

    print "Retrieving (with ua) $url into $file ...\n" unless $config_parms{quiet};
    if ($file eq '/dev/null') {
        $response = $ua->simple_request($request);
    }
    else {
        $response = $ua->simple_request($request, $file);
    }

    if ($response->is_error()) {
        printf "error: %s\n", $response->status_line;
    }
}


# There is an HTML weather page on disk. Parse the weather data out of it and
# save the results in a file so that the parent MH process can read them back
# in.
#
sub parse_weather_sp {
    my $file = shift;
    my $html = &file_read($file);
    my $tmp;

    %Weather = ();
    @Weather_Forecast = ();

print STDERR $html if ($debug);

    ($html =~ m/$parms{city}TT\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{TempOutdoor} = $tmp if ($tmp ne '-');
print STDERR "TempOutdoor|$Weather{TempOutdoor}|\n" if ($debug);

    ($html =~ m/$parms{city}HO\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{TimeObserved} = "$tmp:00" if ($tmp ne '-');
print STDERR "Time Observed|$Weather{TimeObserved}|\n" if ($debug);

    #$Weather{TimeObserved} = str2time($tmp);

#    ($html =~ m/$parms{city}HO\'\]=\"(.*)\"/i) &&
#	($Weather{Conditions} = $1);
#print STDERR "Conditions|$Weather{Conditions}|\n" if ($debug);

    ($html =~ m/$parms{city}TM\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{TempMaxOutdoor} = $tmp if ($tmp ne '-');
print STDERR "TempMaxOutdoor|$Weather{TempMaxOutdoor}|\n" if ($debug);

    ($html =~ m/$parms{city}Tm\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{TempMinOutdoor} = $tmp if ($tmp ne '-');
print STDERR "TempMinOutdoor|$Weather{TempMinOutdoor}|\n" if ($debug);

    ($html =~ m/$parms{city}PO\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{Barom} = $tmp if ($tmp ne '-');
print STDERR "Barom|$Weather{Barom}|\n" if ($debug);

    ($html =~ m/$parms{city}TR\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{HumidOutdoor} = $tmp if ($tmp ne '-');
print STDERR "HumidOutdoor|$Weather{HumidOutdoor}|\n" if ($debug);

    ($html =~ m/$parms{city}DV\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{Wind} = $tmp if ($tmp ne '-');
	$Weather{WindGustDir} = &convert_to_degrees($tmp) if ($tmp ne '-');
	$Weather{WindAvgDir} = &convert_to_degrees($tmp) if ($tmp ne '-');
print STDERR "Wind|$Weather{Wind}|, " if ($debug);
print STDERR "WindGustDir|$Weather{WindGustDir}|, " if ($debug);
print STDERR "WindAvgDir|$Weather{WindAvgDir}|\n" if ($debug);

    ($html =~ m/$parms{city}VV\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{WindAvg} = $tmp if ($tmp ne '-');
	$Weather{WindAvgSpeed} = $tmp if ($tmp ne '-');
print STDERR "WindAvgSpeed|$Weather{WindAvgSpeed}|\n" if ($debug);

    ($html =~ m/$parms{city}RM\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{WindGustSpeed} = $tmp if ($tmp ne '-');
print STDERR "WindGustSpeed|$Weather{WindGustSpeed}|\n" if ($debug);

    ($html =~ m/$parms{city}PP\'\]=\"(.*)\"/i) &&
        ($tmp = $1);
	$Weather{RainTotal} = $tmp if ($tmp ne '-');
print STDERR "RainTotal|$Weather{RainTotal}|\n" if ($debug);

### GET FORECAST
    
    my $forecast = $html;
#    @Weather_Forecast = @forecast;
}


sub save_weather_sp {
    my $file = shift;

    # save the data for import by parent
    my ($key, $perl, $line);
    
    $perl = '%Weather=(' . "\n";
    foreach $key (keys(%Weather)) {
	# cleanup the text
	my $data = $Weather{$key};
	$data =~ s/\s*(\xb0|&deg;)\s*[C]*//g;

	$data =~ s/\s*%\s*//g;
#	$data =~ s;\s*km/h\s*;;g;
	$data =~ s/\s*kPa\s*//g;
	$data =~ s/\s*\s*//g;

	$perl .= '    ' . $key . ' => ' . "'" . $data . "',\n";
    }
    $perl .= ');' . "\n";

    $perl .= '@Weather_Forecast=(';
    for (my $i = 0; $i <= $#Weather_Forecast; $i += 4) { 
	$perl .= "\n    '" . $Weather_Forecast[$i] . "',";
	$perl .= "    '" . $Weather_Forecast[$i+1] . "',";
	$perl .= "    '" . $Weather_Forecast[$i+2] . "',";
	$perl .= "    '" . $Weather_Forecast[$i+3] . "',";
    }
    $perl =~ s/,$//; # remove trailing comma
    $perl .= "\n" . ');' . "\n";

    main::file_write($file, $perl);
}

# convert text wind direction to degrees.
sub convert_to_degrees {
    my $text = shift;
    my $dir;

    ($text eq 'N')   && ($dir = 0);
    ($text eq 'n')   && ($dir = 0);
    ($text eq 'NNE') && ($dir = 22);
    ($text eq 'NE')  && ($dir = 45);
    ($text eq 'Noreste')  && ($dir = 45);
    ($text eq 'ENE') && ($dir = 67);

    ($text eq 'E')   && ($dir = 90);
    ($text eq 'e')   && ($dir = 90);
    ($text eq 'ESE') && ($dir = 112);
    ($text eq 'SE')  && ($dir = 135);
    ($text eq 'Sureste')  && ($dir = 135);
    ($text eq 'SSE') && ($dir = 157);

    ($text eq 'S')   && ($dir = 180);
    ($text eq 's')   && ($dir = 180);
    ($text eq 'SSO') && ($dir = 202);
    ($text eq 'SO')  && ($dir = 225);
    ($text eq 'Suroeste')  && ($dir = 225);
    ($text eq 'OSO') && ($dir = 247);

    ($text eq 'O')   && ($dir = 270);
    ($text eq 'o')   && ($dir = 270);
    ($text eq 'Oeste')   && ($dir = 270);
    ($text eq 'ONO') && ($dir = 292);
    ($text eq 'NO')  && ($dir = 315);
    ($text eq 'Noroeste')  && ($dir = 315);
    ($text eq 'NNO') && ($dir = 337);

    return $dir;
}


