package RPS::Import::MusicAirport2;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days);

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 base 'RPS::Import::Importer';

# map version num to the field order
my %fieldMap = (
    5 => {
        'client_product_id' => 0,
        'isrc'              => 1,
        'artist'            => 2,
        'title'             => 3,
        'price'             => 8,
        'currency'          => 11,
        'format'            => 13,
        'country'           => 14,
        'date'              => 16,
        'units'             => 17,
    },
);

my %countries = ( 'JAPAN' => 'JP', );

#public methods

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

    my $lines    = $args{sheets}->[1];            ## 2nd sheet, after summary
    my $fileObj  = $args{file};
    my $version  = $args{file}->VersionNum();
    my $fileName = $args{file}->OrigFileName();

    #my $version = $args{version}; # cmd-line testing
    #my $fileName = $args{OrigFileName}; # cmd-line testing
    my $sheet_count = 0;
    return undef unless ( defined $lines && defined $version );

    my $offsets      = $fieldMap{$version};
    my $sheet_names  = $args{sheet_names};
    my $header_found = 0;
    my $linenum      = 1;

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $linenum = 1;
        foreach my $line (@$sheet) {
            if ( $header_found == 0 ) {
                $header_found = 1 if ( $line->[ $offsets->{isrc} ] eq "ISRC" );
                $linenum++;
                next;
            }
            if ( $line->[ $offsets->{title} ] ne "" && $line->[ $offsets->{title} ] ne "TITLE" ) {
                my $artist            = $line->[ $offsets->{artist} ];
                my $isrc              = $line->[ $offsets->{isrc} ];
                my $title             = $line->[ $offsets->{title} ];
                my $currency          = $line->[ $offsets->{currency} ];
                my $country           = $countries{ uc( $line->[ $fieldMap{$version}{'country'} ] ) };
                my $client_product_id = $line->[ $fieldMap{$version}{'client_product_id'} ];
                if ( $currency =~ m/^(stirling|gbp|)$/i ) {
                    $currency = "GBP";
                } elsif ( $currency =~ m/^(eur)$/i ) {
                    $currency = "EUR";
                } elsif ( $currency =~ m/^(yen)$/i ) {
                    $currency = "JPY";
                } else {
                    $self->errstr("unknown currency: $currency");
                }

                my ( $dateBegin, $dateEnd ) = $self->_getDates( $sheet_names->[$sheet_count] );
                unless ( defined $dateBegin && defined $dateEnd ) {
                    $self->errstr( "couldn't get dates from " . $line->[ $offsets->{date} ] );
                    return undef;
                }

                my $format = $line->[ $offsets->{format} ];
                if ( $format =~ m/^tt|rbt|ppc|mpc|tdl$/i ) {
                    $format = RPS::File::Sale::FORMAT_RINGTONE;
                } elsif ( $format =~ m/^pdl$/i ) {
                    $format = RPS::File::Sale::FORMAT_DOWNLOAD;
                } elsif ( $format =~ m/^tdl$/i ) {
                    $format = RPS::File::Sale::FORMAT_TETHERED;
                } elsif ( $format =~ m/^str$/i ) {
                    $format = RPS::File::Sale::FORMAT_STREAM;
                } else {
                    $self->errstr("unknown format: $format");
                }

                my $prodtype = RPS::File::Sale::TYPE_TRACK;

                my ($units) = $line->[ $offsets->{units} ] =~ m/^(-?\d+)$/;
                my ($price) = $line->[ $offsets->{price} ] =~ m/^(\d*\.?\d*)$/;

                $price = ( $units != 0 ) ? ( $price / $units ) : 0;

                if ( $units && $price && $title && $artist && $format ) {
                    my $sale = RPS::Import::SaleRec->new();

                    $sale->productType($prodtype);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->isrc($isrc);
                    $sale->artistName($artist);
                    $sale->albumName($title) if ( $prodtype eq RPS::File::Sale::TYPE_ALBUM );
                    $sale->trackName($title) if ( $prodtype eq RPS::File::Sale::TYPE_TRACK );
                    $sale->serviceProductID($client_product_id);
                    $sale->formatType($format);
                    $sale->units($units);
                    $sale->price($price);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);

                    #$args{dumper}($sale); ## for cmd-line testing
                    $self->_insertSale( sale => $sale );
                }
            }
            $linenum++;
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self        = shift;
    my $passed_date = shift;    # end date of period
    $passed_date =~ s/^.* adv-//;
    my ( $dateBegin, $dateEnd );
    if ( $passed_date =~ m/^(\d{4})(\w{3})/ ) {
        my $year   = $1;
        my $month  = $2;
        my %months = (
            'JAN' => '01',
            'FEB' => '02',
            'MAR' => '03',
            'APR' => '04',
            'MAY' => '05',
            'JUN' => '06',
            'JUL' => '07',
            'AUG' => '08',
            'SEP' => '09',
            'OCT' => '10',
            'NOV' => '11',
            'DEC' => '12',
        );
        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $months{$month}, 1 );
        $dateEnd = sprintf( "%04d-%02d-%02d", $year, $months{$month}, Days_in_Month( $year, $months{ uc($month) } ) );
        return ( $dateBegin, $dateEnd );
    }

    return undef;
}

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