# Usage:
#
# 0) setDocument( "http://www.weatheroffice.ec.gc.ca/forecast/city_e.html?yow&b_templatePrint=true" );

# 1) extractTags( weatherHandler, noSymbolTable, conditions );
#    tagsToHtml( "conditions: ->[cCond], ->[cTemp], ->[cPressure], wind at ->[cWind] and ->[cHumidity] humidity" );

# 2) extractTags( weatherHandler, noSymbolTable, forecast );
#    outputDocument( "<td valign=\"top\" width=80 align=\"center\">->[forecast]</td>", 5 );

# 3) extractTags( weatherHandler, noSymbolTable, text );
#    tagsToHtml( "->[text]" );

sub weatherHandler
{
    my $html = shift;
    my $blah = shift; # noSymbolTable isn't for us
    my $type = shift;

    print "-------------[ weatherHandler of type -$type- ]----------------\n";

    if( $type eq "conditions" )
    {
        return currentConditions( $html );
    }
    elsif ( $type eq "forecast" )
    {
        return forecast( $html );
    }
    else
    {
        return text( $html );
    }
}

sub text
{
    my $html = shift;

    my( @rValue ) = ();
    my( $done ) = 0;
    my( $cDiv, $count );
    my( $cCondition, $cWind, $cTemp, $cPressure, $cVisibility, $cHumidity, $cHumidex);

    print "---------------------- Weather Handler (conditions) ----------------------\n";   
    print "rss: $html\n";
    print "---------------------------------------------------------------------------\n\n\n";

    $text="";
    while( $html =~ s/
       <entry>.*?
          <title>(.*?)<\/title>.*?
          <link.*?href=\"(.*?)\"\/>.*?
          <updated>(.*?)<\/updated>.*?
          <published>(.*?)<\/published>.*?
          <category.*?\/>.*?
          <summary.*?>(.*?)<\/summary>.*?
         <id>(.*?)<\/id>.*?
       <\/entry>//six )
    {
        $title=$1;
        $url=$2;
        $description=$5;

        print "title: $1\n";
        print "desc: $description\n";

        if( $title =~ /Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday/gsi )
        {
            if( $description =~ /(Forecast issued .*$)/si )
            {
                if( $date eq "" )
                {
                    $date=$1 . "<br>";
                    $text=$date;
                }
                $description=~s/Forecast issued .*$//si;
            }
            $text.="<a href=\"$url\">$title</a><br>" . "$description" . "<br>";
        }
    }

    print "text: $text";
    #exit 1;

    push @rValue, 
    {
         'text' => $text
    };

    return @rValue;
}

sub forecast
{
    my $html = shift;

    my( @rValue ) = ();
    my( $done ) = 0;
    my( $cTable, $entry, $row );
    my( $textForecast );
    my( $count, $rCount, $done );

    print "---------------------- Weather Handler (forecast) ----------------------\n";
    # print "html: $html\n";
    # exit 1;

    # $count = 1;
    # $done = 0;
    # while( !$done )
    # {
    #     # $cDiv = zUtil::getNthItemNew( $count, $html, "<section class=\"hidden-xs mrgn-tp-lg\"", "</section>" );
    #     $cDiv = zUtil::getNthItemNew( $count, $html, "<details" , "</details>" );
    #     print "$count\n";
    #     #print "table: $cDiv\n";

    #     # this finds the images ... and brief descriptions
    #     if( $cDiv =~ /<h2.*?>Forecast/i )
    #     {
    #         $done=1;
    #     }
    #     $count++;
    #     if( $count > 100 )
    #     {
    #         $done = 1;
    #     }
    # }


    if( $html =~ /<details.*?class=.*wxo-fcst.*?>(.*?)<\/details>/six ) {
        #print "details!: $1\n\n";
        $details=$1;
        if( $details =~ /<div.*?class="div-table".*?>(.*)<\/div>/six ) {
            print "table: $1\n\n";
            $table=$1;
        } else {
            print "no table";
            exit 1;
        }
    }

    # print "fffffffffffffffffffffffffffffffffffffffffffffffffff";
    # $cDiv2 = zUtil::getNthItemNew( 1, $table, '<div class="div-column"', "</div>" );
    # print "\n\n\n\n------$cDiv2-------\n";

    $done = 0;
    $div_count = 1;
    while( ! $done ) {
        # first column in the table is the current conditions and the next window "tonight", etc
        $cDiv2 = zUtil::getNthItemNew( $div_count, $table, '<div', "</div>" );

        if( $cDiv2 =~ /^$/ ) {
            $done = 1;
        } else {
            print "\n\n\n\n------$cDiv2-------\n";

            $entry = "";
            $valid = 0;
            # the first <div> is the header
            # the second <div> is the data
            # (3rd and 4th are the night forecast)
            $header = zUtil::getNthItemNew( 2, $cDiv2, '<div', "</div>" );
            $data = zUtil::getNthItemNew( 3, $cDiv2, '<div', "</div>" );

            print "\nheader: $header\n";
            print "data: $data\n";

            # remove all tags
            $header =~ s|<.+?>| |g;
            print "header clean: $header\n";

            if( $data =~ /<img.*?src=\"(.*?)\".*?\"/s ) {
                # only push the header if we find an image
                $entry .= "$header";

                # print "image!!! $1\n";
                $img = $1;
                $alt = "";
                $entry .= "<a href=\"http://zedd.org/cgi-bin/zii.pl?weather()\"><img border=0 src=\"$img\" alt=\"$alt\"><\/a>";
                $entry .= "<br>";

                $valid = 1;
            }

            if( $data =~ /<strong.*?>(.*?)<\/strong>/s ) {
                # this is the high
                $high = $1;
                # print "Strong!! $1";
                # remove all tags
                $high =~ s|<.+?>| |g;

                $high=~s/&deg;/ c/g;
                $high=~s/°/ /g;
                print "high: $high\n";

                $entry .= "high: $high" . "<br>";
            }
            
            if( $data =~ /<p class="mrgn-bttm-0".*?>(.*?)<\/p>/s ) {
                $conditions = $1;
                print "conditions: $conditions\n";
                $entry .= "$conditions" . "<br>";
            }

            if( $data =~ /<p class="mrgn-bttm-0 pop.*?>(.*?)<\/p>/s ) {
                $pop = $1;
                if( $pop =~ /<small.*?Chance of Precipitation.*?>(.*?)<\/small>/s ) {
                    $pop = $1;
                    $pop =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                    $pop=~s/[^[:print:]]+//g;
                    if ( $pop != "" )
                    {
                        print "pop: $pop\n";
                        $entry .= "pop: $pop" . "<br>";
                    }

                }
            }

            if ( $valid ) {
                push @rValue, 
                { 
                    'forecast' => $entry
                };
            }

        }
        
        # how many nested <div> blocks in the row ? we need to jump them for our next lookup
        $c =()= $cDiv2=~ m/<div/g;
        # print "div without overlap: $c\n";
        $div_count += $c;
    }
    
    # if( $table =~ /<div.*?class="div-column".*?>(.*?)<\/div>/six ) {
    #     print "column: $1\n";
    # }

    #exit 1;
    return @rValue;
    exit 1;
    # print "------$cDiv-------\n";

    $cDiv2 = zUtil::getNthItemNew( 1, $cDiv, "<div class", "</div>" );

    print "\n\n\n===================\n";
    print "------$cDiv2-------\n\n\n\n";
    #exit;

    # each column is:
    #   header
    #   image + text
    #   header
    #   image + text
    $row_one = zUtil::getNthItemNew( 2, $cDiv2, "<div", "</div>" );
    $row_two = zUtil::getNthItemNew( 7, $cDiv2, "<div", "</div>" );
    $row_three = zUtil::getNthItemNew( 12, $cDiv2, "<div", "</div>" );
    $row_four= zUtil::getNthItemNew( 17, $cDiv2, "<div", "</div>" );
    $row_five= zUtil::getNthItemNew( 22, $cDiv2, "<div", "</div>" );

    #print "row1: $row_one\n";
    #print "row2: $row_two\n";
    #print "row3: $row_three\n";
    #print "row4: $row_four\n";
    #print "row5: $row_four\n";

    $count = 1;
    $column = zUtil::getNthItemNew( $count, $cDiv2, "<div", "</div>" );
    while( ! $column =~ /^$/ )
    {
        $element_one = zUtil::getNthItemNew( 2, $column, "<div", "</div>" );
        $element_two = zUtil::getNthItemNew( 3, $column, "<div", "</div>" );
        $element_three = zUtil::getNthItemNew( 4, $column, "<div", "</div>" );
        $element_four = zUtil::getNthItemNew( 5, $column, "<div", "</div>" );

        print "\n\n";
        print "e1: $element_one\n";
        print "e2: $element_two\n";
        print "e3: $element_three\n";
        print "e4: $element_four\n";
        
        $entry="";
        if ( $element_one =~ /<strong title=".*?">(.*?)<\/strong>.*?<br>(.*?)<abbr.*?>(.*?)<\/abbr>/s )
        {
            $day = $1;
            $date = $2;
            $month = $3;

            $date=~s/[^[:print:]]+//g;
            $date=~s/\?//g;

            print "day: $day\n";
            print "date: $date\n";
            print "month: $month\n";

            $entry = "$day $month $date";
        }

        if( $element_two =~ /<img.*?src=\"(.*?)\".*?alt=\"(.*?)\"/s )
        {
            $img=$1;
            $alt=$2;
            print "img: $img\n";
            print "alt: $alt\n";
            $entry .= "<a href=\"http://zedd.org/cgi-bin/zii.pl?weather()\"><img border=0 src=\"$img\" alt=\"$alt\"><\/a>";
            $entry .= "<br>";
            # $entry .= "$day" . "<br>";
            # $entry .= "$alt" . "<br>";
        }
        # <p class="mrgn-bttm-0">Chance of showers</p>
        if( $element_two =~ /<p class=\"mrgn-bttm-0\">([\w\s]*?)<\/p>/ )
        {
            $conditions = $1;
            print "conditions: $conditions\n";
            $entry .= "$conditions" . "<br>";
        }
        # <span class="high wxo-metric-hide" title="max">10&deg;<abbr title="Celsius">C</abbr>
        if( $element_two =~ /<span.*?class=\"high.*?\".*?>(.*?)<abbr.*?>/s )
        {
            $high = $1;
            $high=~s/&deg;/ c/g;
            $high=~s/°/ c/g;
            print "high: $high\n";

            $entry .= "high: $high" . "<br>";
        }
        #<p class="mrgn-bttm-0 pop text-center" title="Chance of Precipitation">
        #    <small> 60%</small>
        #</p>
        if( $element_two =~ /<p class=\"mrgn-bttm-0.*?\".*?title=\"Chance of Precipitation\">.*?<small>(.*?)<\/small>.*?<\/p>/s )
        {
            $pop = $1;
            $pop =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
            $pop=~s/[^[:print:]]+//g;
            if ( $pop != "" )
            {
                print "pop: $pop\n";
                $entry .= "pop: $pop" . "<br>";
            }
        }
          
        if( ! $entry =~ /^$/ ) {
            push @rValue,
            {
                'forecast' => $entry
            };
        }

        $count = $count + 5;
        $column = zUtil::getNthItemNew( $count, $cDiv2, "<div", "</div>" );
        #print "col: $column\n";
    }
    print "SSSSSSSSSSSSSSSSSSSS\n";
    exit;
    return @rValue;

    ## below is old (as of Oct 31st 2016)

    $count=4;
    $div = zUtil::getNthItemNew( $count, $cDiv2, "<div", "</div>" );    
    while( ! $div =~ /^$/ )
    {
        print "======--------------===================\n";
        print "div[$count]: $div\n";

        if( $div =~ /fcst brdr-rght brdr-bttm text-center/ )
        {
            print "============================= Matched!!\n";
            $entry="";
            if( $div =~ /(?s)<strong title.*?>(.*?)<\/strong>.*?<br>(.*?)<abbr.*?>(.*?)<\/abbr>/s )
            {
                $day=$1;
                $date=$2;
                $month=$3;
                
                $day=~s/<abbr><span.*?>(.*?)<\/span><\/abbr>/$1/;
                $day =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                $date=~s/[^[:print:]]+//g;
                
                print "day: $day, date: $date, month: $month\n";
                $entry = "$day $month $date";
                #$entry = "$month $date";

                if( $div =~ /<img.*?src=\"(.*?)\".*?alt=\"(.*?)\"/ )
                {
                    $img=$1;
                    $alt=$2;
                    print "img: $img\n";
                    print "alt: $alt\n";
                    $entry .= "<a href=\"http://zedd.org/cgi-bin/zii.pl?weather()\"><img border=0 src=\"$img\"><\/a>";
                    $entry .= "<br>";
                    $entry .= "$day" . "<br>";
                    $entry .= "$alt" . "<br>";
                }

                if( $div =~ /(?s)<span class=\"high.*?\".*?>(.*?)<\/span>/m )
                {
                    $high=$1;
                    $high=~s/<abbr.*?>(.*?)<\/abbr>/$1/;
                    $high=~s/[^[:print:]]+//g;
                    $high =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                    print "high: ---$high---\n";
                    if ( $high != "" )
                    {
                        $entry .= "high: $high" . "<br>";
                    }
                }
                if( $div =~ /(?s)<span class=\"low.*?\".*?>(.*?)<\/span>/m )
                {
                    $low=$1;
                    $low=~s/<abbr.*?>(.*?)<\/abbr>/$1/;
                    $low=~s/[^[:print:]]+//g;
                    $low =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                    print "low: ---$low---\n";
                    if ( $low != "" )
                    {
                        $entry .= "low: $low" . "<br>";
                    }
                }
                # (?s) says newline matches "."
                if( $div =~ /(?s)<p class=\"pop.*?>(.*?)<\/p>/g )
                {
                    $pop=$1;
                    $pop =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                    $pop =~ s/<.*?>//g;
                    $pop =~ s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                    $pop=~s/[^[:print:]]+//g;
                    print "pop: --$pop--\n";
                    if ( $pop != "" )
                    {
                        $entry .= "pop: $pop" . "<br>";
                    }
                }

                push @rValue, 
                { 
                    'forecast' => $entry
                };
            }
        }

        $count=$count+1;
        $div = zUtil::getNthItemNew( $count, $cDiv2, "<div", "</div>" );       
    }
   
    return @rValue;
}

sub currentConditions
{
    my $html = shift;

    my( @rValue ) = ();
    my( $done ) = 0;
    my( $cDiv, $count );
    my( $cCondition, $cWind, $cTemp, $cPressure, $cVisibility, $cHumidity, $cHumidex);

    print "---------------------- Weather Handler (conditions) ----------------------\n";   
    print "rss: $html\n";

    while( $html =~ s/
       <entry>.*?
          <title>(.*?)<\/title>.*?
          <link.*?href=\"(.*?)\"\/>.*?
          <updated>(.*?)<\/updated>.*?
          <published>(.*?)<\/published>.*?
          <category.*?\/>.*?
          <summary.*?>(.*?)<\/summary>.*?
         <id>(.*?)<\/id>.*?
       <\/entry>//six )
    {
        $title=$1;
        $url=$2;
        $description=$5;

        print "title: $1\n";
        print "desc: $description\n";

        if( $title =~ /Current Conditions/gsi )
        {

            print "=================================\n";
            if( $description =~ /Condition:.*?b>(.*?)<br\/>/si )
            {
                $cCondition=$1;
                $cCondition=~s/\&\#60;//gsi;
                $cCondition=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "cond: $cCondition\n";
            }
            if( $description =~ /Temperature:.*?b>(.*?)<br\/>/si )
            {
                $cTemp=$1;
                $cTemp=~s/\&\#60;//gsi;
                $cTemp=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "temp: $cTemp\n";
            }
            if( $description =~ /Pressure.*?b>(.*?)<br\/>/si )
            {
                $cPressure=$1;
                $cPressure=~s/\&\#60;//gsi;
                $cPressure=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "pressure: $cPressure\n";
            }
            if( $description =~ /Humidity:.*?b>(.*?)<br\/>/si )
            {
                $cHumidity=$1;
                $cHumidity=~s/\&\#60;//gsi;
                $cHumidity=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "humid: $cHumidity\n";
            }
            if( $description =~ /Visibility:.*?b>(.*?)<br\/>/si )
            {
                $cVisibility=$1;
                $cVisibility=~s/\&\#60;//gsi;
                $cVisibility=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "vis: $cVisibility\n";
            }
            if( $description =~ /Wind:.*?b>(.*?)<br\/>/si )
            {
                $cWind=$1;
                $cWind=~s/\&\#60;//gsi;
                $cWind=~s/^\s*(\S*(?:\s+\S+)*)\s*$/$1/;
                print "wind: $cWind\n";
            }

            push @rValue, { 'cCond' => $cCondition,
                            'cTemp' => $cTemp,
                            'cPressure' => $cPressure,
                            'cVisibility' => $cVisibility,
                            'cHumidity' => $cHumidity,
                            'cWind' => $cWind
                           };
        }
    }

    return @rValue;
}

return 1;

