package RPS::Import::AmazonCloud::v1;

use strict;

use lib '/app/tools/common/lib';
use Common::Date;
use Common::Country;
use Common::CurrencyFormat;

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

use Data::Dumper;
use Date::Calc qw(Days_in_Month Decode_Month);

sub _fieldMap {
    {
        # header
        currencyCode     => 'A',
        dateBegin        => 'A',

        # detail
        productType      => 'F',
        albumName        => 'M',
        labelName        => 'O',
        artistName       => 'L',
        isrc             => 'E',
        trackName        => 'N',
        units            => 'H',
        upc              => 'C',
    }
}

sub _headerIdentifier { ( albumName => 'ALBUM_NAME' ) }

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;
    }
}

sub formatType { return RPS::File::Sale::FORMAT_STREAM; }

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

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

sub currencyCode {
    my $self = shift;
    return $self->{_currencyCode} if( $self->{_currencyCode} ); # from header; see _preProcess
}

sub countryCode {
    my $self = shift;
    return $self->{_countryCode} if( $self->{_countryCode} ); # from header; see _preProcess
}

sub _isValidSaleRecord {
    my $self = shift;
    my $units = $self->units();

    return if( !$units ); # skip lines without units

    return $self->SUPER::_isValidSaleRecord();
}

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

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

    my $linenum = 1;
    foreach my $line(@{ $args{lines} }) {

        $self->{line} = $line;

        # Get the country and currency codes from the header
        #
        if( $linenum == 1 )
        {
            my $curstr = $self->_getByFieldName('currencyCode');
            $curstr =~ s/\s*$//g;

            if( $curstr =~ /amazon (\w\w) cloud services \(cost in (\w*)\)$/i )
            {
                $self->{_countryCode}  = $1;
                $self->{_currencyCode} = $2;
            }
            elsif( $curstr =~ /amazon (\w\w) cloud services$/i )
            {
                my $cf = Common::CurrencyFormat->new( countryCode => $1 );
                if( $cf )
                {
                    $self->{_countryCode}  = $1;
                    $self->{_currencyCode} = $cf->{CurrencyCode};
                    $self->fail("Unable to determine currency format from '$1'") if( ! $cf->{CurrencyCode} ); # shouldn't happen but check anyway
                }
                else
                {
                    $self->fail("Unable to determine currency format from '$1'");
                }
            }
            else
            {
                print STDERR "_preProcess: WARNING: Unable to decode '$curstr' in header\n";
                $self->fail("Unable to decode country/currency code from header");
            }
        }

        # Get the date from the header
        #
        if( $linenum == 2 )
        {
            my $dt = $self->_getByFieldName('dateBegin');
            if( $dt =~ /^(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) # MM/DD/YYYY
            {
                my( $year, $month ) = ( $3, $1 );
                $self->{_startDate} = sprintf( "%04d-%02d-%02d", $year, $month, 1 );

                $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month) )

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

            last; # done processing header
        }

        $linenum++;
    }
}

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