package RPS::Import::AudioJelly;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

use lib '/app/tools/rps/lib';
use RPS::DB::Item::Client;

use lib '/app/tools/common/lib';
use Common::Consts qw(%COUNTRY_TO_CODE);

use lib '/app/tools/data_classes/lib';

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

my %fieldMap = (
    1 => {
        date        => 2,
        title       => 3,
        label       => 4,
        artist      => 6,
        country     => 7,
        gross_price => 8,
        price       => 13,
    },
    2 => {
        catalog => 4,
        isrc    => 6,
        date    => 3,
        title   => 1,
        label   => 5,
        artist  => 7,
        country => 8,
        price   => 14,
    },
);

#my %currency_map = (
#    AU  => 'USD',
#    SE  => 'EUR',
#    US  => 'USD',
#    GB  => 'GBP',
#    MO  => 'USD',
#    FI  => 'EUR',
#    LU  => 'EUR',
#    SI  => 'EUR',
#    FR  => 'EUR',
#    ZA  => 'USD',
#    CA  => 'USD',
#    DE  => 'EUR',
#    RU  => 'USD',
#    ES  => 'EUR',
#    EU  => 'EUR',
#    DK  => 'EUR',
#    PA  => 'USD',
#);

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',
);

#public methods

sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $fileObj     = $args{file};
    my $version     = $args{file}->VersionNum();
    my $fileName    = $args{file}->OrigFileName();
    my $serviceID   = $args{file}->ServiceID;
    my $sheet_count = 0;

    return undef unless ( defined $args{sheets} && defined $version );

    my $offsets      = $fieldMap{$version};
    my $sheet_names  = $args{sheet_names};
    my $header_found = 0;
    my $linenum      = 1;
    my ( $dateBegin, $dateEnd ) = $self->_getDates($fileName);

    my $clientID = $args{client_id};

    if ( !$clientID ) {
        $clientID = $args{clientID};
    }

    if ( !$clientID ) {
        $self->errstr("couldn't get client ID");
        print STDERR "couldn't get client ID\n";
        return undef;
    }

    #print STDERR "Args: ".Dumper(\%args);

    print STDERR "client ID: $clientID\n";

    my $currencyCode;

    my $client = RPS::DB::Item::Client->Lookup( client_id => $clientID );
    my $country_code = $client->country_code;
    $currencyCode = $gCountryCodeToCurrencyMap{$country_code};

    if ( !$currencyCode ) {
        $self->errstr("couldn't get base currency from country of origin: $country_code");
        print STDERR "couldn't get base currency from country of origin: $country_code\n";
        return undef;
    } elsif ( $currencyCode ne "GBP" ) {
        $self->errstr( "Unknown amount threshold for currency $currencyCode and " . "track or album determination" );
        print STDERR "Unknown amount threshold for currency $currencyCode and " . "track or album determination\n";
        return undef;
    }

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $linenum = 1;
        if ( $sheet_names->[$sheet_count] !~ /summary/i ) {

            foreach my $line (@$sheet) {
                my $country = $line->[ $offsets->{country} ];

                #my $currency            = $currency_map{$country};
                my $track  = $line->[ $offsets->{title} ];
                my $artist = $line->[ $offsets->{artist} ];
                my $format = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $product;
                my $units       = 1;
                my $price       = $line->[ $offsets->{price} ];
                my $gross_price = $line->[ $offsets->{gross_price} ];

                if ( ( $currencyCode eq "GBP" ) && ( $gross_price > 1.99 ) ) {
                    $product = RPS::File::Sale::TYPE_ALBUM;
                } else {
                    $product = RPS::File::Sale::TYPE_TRACK;
                }

                my $label   = $line->[ $offsets->{label} ];
                my $catalog = $line->[ $offsets->{catalog} ] if ( defined $offsets->{catalog} );
                my $isrc    = $line->[ $offsets->{isrc} ] if ( defined $offsets->{isrc} );
                my ( $dateBegin, $dateEnd ) = _getDates( $line->[ $offsets->{date} ] );
                $price /= $units if ( $units != 0 );
                $track =~ s/\(.*$//;
                $track =~ s/ 320 kbps//;

                if ( $units && $artist && $country && $price && $track && $track !~ /Track \/ album name/ ) {

                    unless ( defined $dateBegin && defined $dateEnd ) {
                        print STDERR "Couldn't get dates from: " . $line->[ $offsets->{date} ] . "\n";
                        $self->errstr( "couldn't get dates from: " . $line->[ $offsets->{date} ] );
                        return undef;
                    }

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

                    $sale->mediaType(2) if ( $format =~ /video/i );
                    $sale->productType($product);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->labelName($label);
                    $sale->trackName($track);
                    $sale->artistName($artist);
                    $sale->formatType($format);
                    $sale->serviceProductID($catalog) if ( defined $offsets->{catalog} );
                    $sale->isrc($isrc)                if ( defined $offsets->{isrc} );
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currencyCode);
                    $sale->lineNum($linenum);

                    $self->_insertSale( sale => $sale );
                }

#else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " - u:".$units." p:".$price." a:".$artist." t:".$track." f:".$format."\n"; }
                $linenum++;
            }
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my ( $smonth, $syear, $sday, $emonth, $eyear, $eday );
    my $passed_date = shift;
    if ( $passed_date =~ m/(\d{4})-(\d+)-(\d+)/ ) {
        $syear  = $1;
        $smonth = $2;
        $sday   = $3;
    }
    if ( $syear && $smonth ) {
        return ( $syear . "-" . $smonth . "-01", $syear . "-" . $smonth . "-" . Days_in_Month( $syear, $smonth ) );
    }
    return undef;
}

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