#!/usr/bin/perl
use warnings;
use strict;

=head1 NAME

 enter_nfl_scores.pl  - A tool to get scores from nfl.com. 

=head1 SYNOPSIS

 enter_nfl_scores.pl [options] [week or week range] [year] [config_file]
 Options:
        --help           brief help message
        --man            full documentation

Notes: week defaults to the first week. year defaults to 2007.
config_file defaults to 'nfl.config' in the current directory.

=head1 VERSION

 author   dwmyers
 date     10/14/2007
 modified 10/16/2007

=head1 DESCRIPTION

 enter_nfl_scores.pl - A tool to get scores from nfl.com. 
This program uses HTML::TreeBuildwer to get div blocks with game scores. Once
parsed, this program will enter them into a MySQL database.

=head1 COPYRIGHT

    This program is copyrighted 2007 by David Myers. All rights are
    reserved.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut

use DBI;
use LWP::UserAgent;
use HTML::TreeBuilder;
use Config::Simple;
use Getopt::Long;
use Pod::Usage;

my $help = 0;
my $man  = 0;

GetOptions(
    'help|?'          => \$help,
    man               => \$man,
) or pod2usage(2);

pod2usage( -exitval => 0, -verbose => 1 ) if $help;
pod2usage( -exitval => 0, -verbose => 2 ) if $man;

my $week        = shift || 1;
my $year        = shift || 2007;
my $config_file = shift || "nfl.config";
my $start       = $week;
if ( $week =~ /\-/ ) {
    ( $start, $week ) = split /\-/, $week;
}

my %db_hash;
Config::Simple->import_from( $config_file, \%db_hash );

my $db       = "nfl_$year";
my $user     = $db_hash{"${db}.user"};
my $pass     = $db_hash{"${db}.pass"};
my $db_table = $db_hash{"${db}.table"};

my $dbh = DBI->connect( "DBI:mysql:$db", "$user", "$pass" )
  or die("Cannot connect to the database $!");

for my $w ( $start .. $week ) {
    print "\n\n************\n";
    printf "*  Week %-2d *\n", $w;
    print "************\n\n";
    my $url   = "http://www.nfl.com/scores?season=${year}&week=Week+$w";
    my $agent = new LWP::UserAgent;
    my $page  = $agent->get($url);
    if ( $page->is_success() ) {
        my $root     = HTML::TreeBuilder->new_from_content( $page->content() );
        my @all_divs = $root->look_down(
            '_tag', 'div',
            sub {
                $_[0]->attr('class')
                  and $_[0]->attr('class') eq "scoreBox";
            }
        );
        for my $div (@all_divs) {
            my $status = $div->look_down(
                '_tag', 'div',
                sub {
                    $_[0]->attr('class')
                      and $_[0]->attr('class') =~ /^scoreBoxHeader/;
                }
            );
            if ($status) {
                next unless ( $status->as_text =~ /FINAL/ );
            }
            my @scores = $div->look_down(
                '_tag', 'div',
                sub {
                    $_[0]->attr('class')
                      and $_[0]->attr('class') eq "scoresBoxTeamScore";
                }
            );
            my @teams = $div->look_down(
                '_tag', 'div',
                sub {
                    $_[0]->attr('class')
                      and $_[0]->attr('class') eq "scoresBoxTopTeamLogo";
                }
            );
            my @names = map { just_symbol($_) } @teams;
            if ( @scores and @names ) {
                my $v_score = $scores[0]->as_text();
                my $h_score = $scores[1]->as_text();
                printf "%-3s %-2d - %-3s %-2d\n", $names[0], $v_score,
                  $names[1], $h_score;
                my $sql =
                    "select id from $db_table where week=$w and "
                  . "visitor='$names[0]' and home='$names[1]'";
                my $sth = $dbh->prepare($sql);
                $sth->execute;
                my ($id) = $sth->fetchrow_array();
                unless ( defined($id) ) {

                    my $sql =
                        "insert into $db_table "
                      . "(week,visitor,visit_score,home,home_score) "
                      . "VALUES ($w,'$names[0]',$v_score,'$names[1]',$h_score)";
                    my $sth = $dbh->prepare($sql);
                    $sth->execute;
                }
            }
        }
    }
    sleep 15 if ( $w < $week );
}

$dbh->disconnect;

sub just_symbol {
    my $tag    = shift;
    my $href   = $tag->look_down( '_tag', 'a' )->attr('href');
    my $symbol = "XXX";
    $symbol = $1 if ( $href =~ /team=(\w\w\w?)$/ );
    return $symbol;
}