package BookPub::RDAS::Parser::SaleData::Amazon::Files;

use lib '/app/tools/rdas/lib';
use base 'RDAS::Parser::Item';

use Data::Dumper;
use URI::Escape;

sub value {
    my $token = shift->token() || return;
    my @result;

    my @rows = $token->look_down( _tag => 'tr', class => 'rep-dash-entry' );
    return unless (@rows);

    foreach my $row (@rows) {
        my $file = _getLink($row);
        push( @result, $file ) if ($file);
    }

    return \@result;
}

sub _getLink {
    my $row = shift;
    my @cells = $row->look_down( _tag => 'td', class => 'rep-dash-entry' );
    my $a;
    my $reportID;
    my $start;
    my $end;
    my $filename;
    my $countryCode;

    foreach my $cell (@cells) {
        $a = $cell->find('a');
        if ($a) {
            my $onClick = $a->attr('onclick');
            if ( $onClick =~ m/reportId=(\w*|\d*)&/ ) {
                $reportID = $1;
                if ( $onClick =~ m/reportTitle=(.*?)\'/ ) {
                    $filename = $1;
                    $link =
                        "/gp/vendor/members/digital-media/download?ie=UTF8&reportId="
                      . $reportID
                      . "&reportTitle="
                      . $filename
                      . "&asexcel.x=1&headerFormat=dataWithHeaders";

                    $filename = uri_unescape($filename);

                    ( $start, $end ) = _getDate($filename);

                    if ($filename) {
                        $filename =~ s/ /_/g;
                        $filename .= ".xls";
                    }

                }
            }
        }

        # Going to pull the country code from the Marketplace column (if it exists for this account).
        my $text = $cell->as_text();
        if ($text) {
            $text =~ s/^\s+//;
            $text =~ s/\s+$//;
            if ( $text =~ /^\w{2}$/ ) {
                $countryCode = $text;
            }
        }

    }

    if ( $countryCode eq 'GB' ) {
        $countryCode = 'UK';
    }

    return unless ( $link && $a );

    # If we found a country code in the row, we need to add it to the file name now
    # in order to match the feed.
    if ( $countryCode && $filename =~ /(\w{5}_)(.+)/ ) {
        $filename = $1 . $countryCode . "_" . $2;
    }

    my $result = {
        start       => $start,
        end         => $end,
        filename    => $filename,
        reportID    => $reportID,
        title       => $title,
        countryCode => $countryCode,
        link        => $link
    };

    return $result;
}

sub _getDate {
    my $file = shift || return;
    return unless ( $file =~ /\w+ (\d+\/\d+\/\d+) \w+ (\d+\/\d+\/\d+)/ );
    my $start = $1;
    my $end   = $2;

    # Need to be able to detect euro dates, which shouldn't be too bad
    # because Amazon always sets the day to 1.
    # So we'll turn 1/3/2011 into 3/1/2011.
    if ( $start =~ /^1\/(\d+)\/(\d+)$/ ) {
        $start = $1 . "/1/" . $2;
    } elsif ( $start =~ /^(28|29|30|31)\/(\d+)\/(\d+)$/ )    # DD/MM/YYYY
    {
        # Ok, looks like some start dates are the last day of the previous month, with
        # the end date being the last day of the month.
        #
        $start = $2 . "/" . $1 . "/" . $3;     # MM/DD/YYYY
        $start = new Common::Date("$start");
        $start->addDays(1);

        if ( $end =~ /^(28|29|30|31)\/(\d+)\/(\d+)$/ )    # DD/MM/YYYY
        {
            $end = $2 . "/" . $1 . "/" . $3;              # MM/DD/YYYY
        }
        $end = new Common::Date("$end");

        return ( "$start", "$end" );
    }

    if ( $end =~ /^1\/(\d+)\/(\d+)$/ ) {
        $end = $1 . "/1/" . $2;
    }

    $start = new Common::Date("$start");
    $end   = new Common::Date("$end");

    # Amazon specifies the end date as the first of the following month.  Let's
    # back it up one day so it is actually the last day of the period.
    $end->addDays(-1);

    return ( "$start", "$end" );
}

1;
