package RPS::Import::ICAgency;

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 = (
    1 => {
        'client_product_id' => 0,
        'isrc'              => 1,
        'artist'            => 2,
        'title'             => 3,
        'album'             => 4,
        'price'             => 8,
        'currency'          => 11,
        'format'            => 13,
        'country'           => 14,
        'date'              => 16,
        'units'             => 17,
    },
    2 => {
        'client_product_id' => 0,
        'isrc'              => 2,
        'artist'            => 3,
        'title'             => 4,
        'album'             => 5,
        'price'             => 9,
        'currency'          => 12,
        'format'            => 14,
        'country'           => 15,
        'date'              => 17,
        'units'             => 18,
    },
    3 => {
        'client_product_id' => 0,
        'isrc'              => 1,
        'artist'            => 3,
        'title'             => 4,
        'album'             => 5,
        'price'             => 9,
        'currency'          => 12,
        'format'            => 14,
        'country'           => 15,
        'date'              => 17,
        'units'             => 18,
    },
    4 => {
        'client_product_id' => 0,
        'isrc'              => 2,
        'artist'            => 4,
        'title'             => 5,
        'album'             => 6,
        'price'             => 10,
        'currency'          => 13,
        'format'            => 15,
        'country'           => 16,
        'date'              => 18,
        'units'             => 19,
    },
);

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

#public methods

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

    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 $args{sheets} && 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) {
            my $artist            = $line->[ $offsets->{artist} ];
            my $isrc              = $line->[ $offsets->{isrc} ];
            my $title             = $line->[ $offsets->{title} ];
            my $album             = $line->[ $offsets->{album} ];
            my $currency          = $line->[ $offsets->{currency} ];
            my $country           = $countries{ uc( $line->[ $fieldMap{$version}{'country'} ] ) };
            my $client_product_id = $line->[ $fieldMap{$version}{'client_product_id'} ];
            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   = lc $line->[ $offsets->{format} ];
            my $prodtype = RPS::File::Sale::TYPE_TRACK;
            my ($units)  = $line->[ $offsets->{units} ];
            my ($price)  = $line->[ $offsets->{price} ];

            $price = ( $units != 0 ) ? ( $price / $units ) : 0;
            if ( $units && $price && $title && $format && $title ne "Title" ) {
                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");
                }

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

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

                $sale->productType($prodtype);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->isrc($isrc);
                $sale->artistName($artist);
                $sale->albumName($album) if ( $album ne "" );
                $sale->trackName($title);
                $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 );
            }

            #else { print STDERR "Skipping line: " . $linenum . " - u:".$units." p:".$price." a:".$artist." t:".$title." f:".$format."\n"; }
            $linenum++;
        }
        $sheet_count++;
    }
    return $linenum;
}

#
# Private methods
#

sub _getDates {
    my $self        = shift;
    my $passed_date = shift;
    my ( $year, $month ) = split( "_", $passed_date );
    my $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
    my $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) );
    return ( $dateBegin, $dateEnd );
    return undef;
}

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