package BookPub::RDAS::Parser::SaleData::Apple::Item::Files;

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

use Common::Date;

use Data::Dumper;

sub value {
    my $token = shift->token();

    my @results;

    return unless ($token);

    my @rows = $token->find('tr');

    my $hasTypeCol = 0;

    foreach my $row (@rows) {

        # Skip the header row
        # But first, check for the revenue type column.
        if ( $row->attr('class') eq 'labels' ) {
            my @cols = $row->find('td');
            if ( $cols[2]->as_text() eq 'Revenue Type' ) {
                Log->debug("Found revenue type column");
                $hasTypeCol = 1;
            }
            next;
        }

        my $record = _parseRecord( $row, $hasTypeCol );

        push( @results, $record ) if ($record);

    }

    return \@results;
}

sub _parseRecord {
    my $row = shift || return;
    my $hasTypeCol = shift;

    my @cols = $row->find('td');

    # If there are not at least 5 columns, then we will assume this isn't a valid 'file' row.
    # We could look for the text 'There are no reports that match your request.' in column 1, but
    # that seems more fragile.
    #
    return undef unless ( scalar @cols >= 5 );

    my $result = {
        date     => $cols[0]->as_text(),
        region   => $cols[1]->as_text(),
        units    => $cols[ 2 + $hasTypeCol ]->as_text(),
        revenue  => $cols[ 3 + $hasTypeCol ]->as_text(),
        currency => $cols[ 4 + $hasTypeCol ]->as_text(),
    };

    if ( $cols[ 5 + $hasTypeCol ] && ref( $cols[ 5 + $hasTypeCol ] ) ) {
        my $input = $cols[ 5 + $hasTypeCol ]->find('input');
        $result->{name} = $input->attr('name') if ($input);
    }

    my $date = new Common::Date( $result->{date} );

    $result->{start} = $date->monthBegin();
    $result->{end}   = $date->monthEnd();

    Log->debug( "File Record: " . Dumper $result );

    return $result->{name} ? $result : undef;
}

1;
