package RPS::Import::GoogleMusic::v5;

use strict;

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use base 'RPS::Import::Importer';

sub _fieldMap {
    {
        # header
        dateBegin   =>  'C',
        dateEnd     =>  'D',

        # detail
        countryCode =>  'B',
        upc         =>  'G',
        isrc        =>  'H',
        artistName  =>  'I',
        trackName   =>  'J',
        albumName   =>  'K',
        labelName   =>  'M',
        productType =>  'D',
        price       =>  'T',
    }

}

sub _unverifiedFieldMap {
    {
        quantityPurchased => 'E',
        quantityUsed      => 'F',
    }
}

sub _headerIdentifier { ( upc => 'UPC' ) }

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('productType');
    if( $type =~ /^t$/i )
    {
        return RPS::File::Sale::TYPE_TRACK;
    }
    elsif( $type =~ /^a$/i )
    {
        return RPS::File::Sale::TYPE_ALBUM;
    }
    $self->fail( "Unknown product type '$type'" );
}

sub formatType{ RPS::File::Sale::FORMAT_DOWNLOAD }

sub mediaType{ RPS::DB::Item::MediaType::kMediaTypeAudio }

sub currencyCode {
    my $self = shift;
    return $self->{_currencyCode};  # see _preProcess
}

sub units {
    my $self = shift;
    my $qtyPurchased  = $self->_getByFieldName('quantityPurchased') || 0;
    my $qtyUsed       = $self->_getByFieldName('quantityUsed') || 0;

    return $qtyPurchased - $qtyUsed;
}

sub saleDates {
    my $self = shift;
    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} ); # from header; see _preProcess
}

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info( "Starting _preProcess" );
    $self->SUPER::_preProcess(%args);

    my $getDateFlag;     # set if we find a date header
    my $getCurrencyCode; # set if we find a revenue header

    my $foundDetails;    # set once we find the header for the details section

    my $revenue;
    my $units;

    foreach my $line(@{ $args{lines} }) {

        $self->{line} = $line;

        # Get the date from the header
        #
        if( !$getDateFlag && $self->_getByFieldName('dateBegin') =~ /start_date/i )
        {
            $getDateFlag = 1;
        }
        elsif( !$self->{_startDate} && $getDateFlag )
        {
            my $dt = $self->_getByFieldName('dateBegin');

            if( $dt =~/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/ ) # DD/MM/YYYY or MM/DD/YYYY
            {
                # Assume the date is US (MM/DD/YYYY), but we'll accomodate UK if needed
                #
                my $startDate = sprintf( "%04d-%02d-%02d", $3, $1, $2 );

                my $_endDate = $self->_getByFieldName('dateEnd');
                my($m, $d, $y) = split("/", $_endDate);
                my $endDate = sprintf( "%04d-%02d-%02d", $y, $m, $d);

                ($startDate, $endDate) = $self->_getDates( date_begin => $startDate, date_end => $endDate );

                $self->{_startDate} = $startDate;
                $self->{_endDate}   = $endDate;

            }
            elsif( $dt =~/^(\d{4})-(\d{1,2})-(\d{1,2})$/ ) # YYYY-MM-DD
            {
                # Assume the date is US (MM/DD/YYYY), but we'll accomodate UK if needed
                #
                my $startDate = sprintf( "%04d-%02d-%02d", $1, $2, $3 );

                my $_endDate = $self->_getByFieldName('dateEnd');
                my($y, $m, $d) = split("-", $_endDate);
                my $endDate = sprintf( "%04d-%02d-%02d", $y, $m, $d);

                ($startDate, $endDate) = $self->_getDates( date_begin => $startDate, date_end => $endDate );

                $self->{_startDate} = $startDate;
                $self->{_endDate}   = $endDate;
            }
            else
            {
                print STDERR "_preProcess: WARNING: Unable to decode date '$dt'\n";
                $self->errstr("Unable to decode date '$dt' in header");
                return undef;
            }
        }

        # Get the currency code from the header
        #
        if( !$getCurrencyCode && $self->_getByFieldName('price') =~ /^partner_revenue_(\w{3})$/i )
        {
            $getCurrencyCode = 1;
            $self->{_currencyCode} = $1;
        }

    }

}

# _getDates: helper method to process US or UK formatted dates.
#
# The end date is checked to see if it's a US or UK-formatted date, with
# the assumption that the day will be be greater than 12 (most likely
# between 28-31). The begin date determines the reporting period, which
# will span one month regardless of the end date specified in the file.
#
sub _getDates {
    my $self  = shift;
    my %args  = @_;

    my $_dateBegin = $args{date_begin};  # YYYY-MM-DD or YYYY-DD-MM
    my $_dateEnd   = $args{date_end};    # YYYY-MM-DD or YYYY-DD-MM

    my $dateBegin = $_dateBegin;

    my( $beginYear, $beginMonth, $beginDay ) = split("-", $_dateBegin);
    my( $endYear,   $endMonth,   $endDay   ) = split("-", $_dateEnd);

    if( $endMonth > 12 )
    {
        $dateBegin = join("-", $beginYear, $beginDay, $beginMonth); # swap the month/day fields
    }

    return $self->SUPER::_getDates( date_begin => $dateBegin );
}

###
1;# Play nicely.
###
