package RPS::Import::Amazon;
use strict;

use Date::Calc qw(Days_in_Month Decode_Month);

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

use lib '/app/tools/common/lib';
use Common::Util qw(normalize_upc normalize_isrc);

#private constants
use constant FIELD_SVCPRODID    => 0;
use constant FIELD_CLIPRODID_A  => 1;
use constant FIELD_UPC          => 2;
use constant FIELD_CLIPRODID_T  => 3;
use constant FIELD_ISRC         => 4;
use constant FIELD_PRODTYPE     => 5;
use constant FIELD_UNITS        => 6;
use constant FIELD_PRICE        => 7;
use constant FIELD_ARTIST       => 9;
use constant FIELD_ALBUM        => 10;
use constant FIELD_TRACK        => 11;
use constant FIELD_LABEL        => 12;

use constant FORMAT => RPS::File::Sale::FORMAT_DOWNLOAD;

use base 'RPS::Import::Importer';

my %gCountryCodeToCurrencyMap =
(
    'US' => 'USD',
    'JP' => 'JPY',
    'NZ' => 'NZD',
    'IS' => 'ISD',
    'JM' => 'JMD',
    'EU' => 'EUR',
    'GB' => 'GBP',
    'CA' => 'CAD',
    'AU' => 'AUD',
    'DE' => 'EUR',
    'FR' => 'EUR',
    'BE' => 'EUR',
    'IT' => 'EUR',
    'CH' => 'CHF',
    'PL' => 'PLN',
    'LV' => 'LVL',
    'LT' => 'LTL',
    'KR' => 'KRW',
    'ZA' => 'ZAR',
    'GR' => 'EUR',
    'NL' => 'EUR',
);

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

    my $lines = $args{lines};
    my $fileObj = $args{file};
    my $version = $self->_version();
    my $fileName = $fileObj->OrigFileName();
    return 0 unless $lines;

    my $currency_code = 'USD';
    my $country_code = 'US';

    if($version == 6){
        $currency_code = 'GBP';
        $country_code = 'GB';
    }

    my $dates;

    if($version == 2){
        $dates = $lines->[0][0];
    }
    elsif(($version == 6) || ($version == 7)){
        $dates = $lines->[1][0];
    }
    else{
        $dates = $fileName;
    }

    if ($version == 7)
    {
        my $countryRow = $lines->[0][0];

        if ( $countryRow =~ m/Amazon (\w{2}) MP3 Sales$/ )
        {
            $country_code = $1;
            $currency_code = $gCountryCodeToCurrencyMap{$country_code};

            unless( $currency_code )
            {
                $self->errstr("Unable to determine currency for country: $country_code");
                print STDERR "Unable to determine currency for country: $country_code\n";
                return 0;
            }
        }
        else
        {
            # Example:
            # Amazon CH MP3 Sales (Cost in Euros)
            $countryRow =~ m/Amazon (\w{2}) MP3 Sales \(Cost in (.+)\)$/;
            $country_code = $1;
            my $currency = $2;

            if ($currency eq 'US Dollars')
            {
                $currency_code = 'USD';
            }
            elsif ($currency eq 'Euros')
            {
                $currency_code = 'EUR';
            }
            else
            {
                $currency_code = $gCountryCodeToCurrencyMap{$country_code};
                unless( $currency_code )
                {
                    $self->errstr("currency not recognized: $currency");
                    print STDERR "currency not recognized: $currency\n";
                    return 0;
                }
            }
        }


        #foreach my $countryCode(keys %gCountryCodeToCurrencyMap){
        #    if($1 =~ /$countryCode/){
        #        $country_code = $countryCode;
        #        $currency_code = $gCountryCodeToCurrencyMap{$countryCode};
        #    }
        #}
    }

    #my $dates = $version == 2 ? $lines->[0][0] : $fileName;
    my ($dateBegin, $dateEnd) = $self->_getDates($dates);

    unless ($dateBegin && $dateEnd)
    {
        $self->errstr("couldn't get dates");
        print STDERR "date source: $dates\n";
        return 0;
    }

    my %errors = ();
    my $linenum = 1;
    foreach my $line(@$lines)
    {
        my $free = 0;
        my ($cliProdID, $upc, $isrc);
        my $prodType  = uc $line->[FIELD_PRODTYPE];
        my $svcProdID = $line->[FIELD_SVCPRODID];

        if ($prodType eq 'A')
        {
            $cliProdID  = $line->[FIELD_CLIPRODID_A];
            $upc        = normalize_upc($line->[FIELD_UPC]) || normalize_upc($cliProdID);
        }
        elsif ($prodType eq 'T')
        {
            $cliProdID  = $line->[FIELD_CLIPRODID_T];
            $isrc       = normalize_isrc($line->[FIELD_ISRC]);
            $upc        = normalize_upc($line->[FIELD_UPC]) || normalize_upc($line->[FIELD_CLIPRODID_A]);
        }

        my $album   = $line->[FIELD_ALBUM];
        my $artist  = $line->[FIELD_ARTIST];
        my $label   = $line->[FIELD_LABEL];
        my $price   = abs($self->numeric($line->[FIELD_PRICE]));
        my $return  = 1 if( $self->numeric($line->[FIELD_PRICE]) < 0 );
        my $track   = $line->[FIELD_TRACK];
        my $units   = $self->numeric($line->[FIELD_UNITS]);
        $units *= -1 if( $return && $units > 0 );

        if ($units && ( $track !~ /Track_Name/ || $album !~ /ALBUM_NAME/))
        {
                unless ($prodType =~ /(A|T)/i || $errors{$prodType})
                {
                    print STDERR "unknown prod type: ".$line->[FIELD_PRODTYPE]." ($linenum)\n";
                    $errors{$prodType} = 1 unless ($prodType eq '');
                }

            if(!$price){
                $price = 0;
            }

            my $sale = RPS::Import::SaleRec->new();

            $sale->albumName($album);
            $sale->artistName($artist);
            $sale->clientProductID($cliProdID);
            $sale->dateBegin($dateBegin);
            $sale->dateEnd($dateEnd);
            $sale->formatType(FORMAT);
            $sale->isrc($isrc);
            $sale->labelName($label);
            $sale->lineNum($linenum);
            $sale->upc($upc);
            $sale->price($price);
            $sale->productType($prodType);
            $sale->serviceProductID($svcProdID);
            $sale->free($free);
            $sale->trackName($track);
            $sale->units($units);
            $sale->currencyCode($currency_code);
            $sale->countryCode($country_code);

            #$args{dumper}($sale);
            $self->_insertSale(sale => $sale);
        }
        #else { print STDERR "skip: ($linenum) p: $price u: $units t:".$track." a:".$album."\n"; }
        $linenum++;
    }

    return $linenum;
}

#
# Private methods
#


sub _getDates
{
    my $self = shift;
    my $source = shift;

    my ($month, $year);
    if ($source =~ m/[\s_\-]+(\w\w\w)(\d\d)\D/)
    {
        ($month, $year) = ($1, $2);
        $month = Decode_Month($1);
        $year += 2000 if ($year < 2000);
    }
    elsif ($source =~ m/^(\d+)\D\d+\D(\d+)\D/)
    {
        ($month, $year) = ($1, $2);
    }

    return undef unless ($month && $year > 2000);
    return (
        sprintf("%04d-%02d-01", $year, $month),
        sprintf("%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month))
    );
}

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