package RPS::Import::TouchNGoRevisedV2;

use strict;

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

use lib '/app/tools/common/lib';
use Common::Consts qw(%COUNTRY_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 = (
    2 => {
        isrc_upc         => 0,
        artist           => 1,
        title            => 2,
        downloads        => 3,
        download_revenue => 4,
        streams          => 5,
        stream_revenue   => 6,
        free             => 7,
        label            => 9,
        label_percent    => 10,
    },
    '2_consignment' => {
        upc           => 0,
        catalog_title => 2,
        units         => 4,
        revenue       => 11,
    }
);

#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( date_begin => $fileName, type => 'us' );

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

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

            foreach my $line (@$sheet) {
                my $country  = "US";
                my $currency = "USD";
                my $product;

                my $isrc_upc         = $line->[ $offsets->{isrc_upc} ];
                my $title            = $line->[ $offsets->{title} ];
                my $artist           = $line->[ $offsets->{artist} ];
                my $label            = $line->[ $offsets->{label} ];
                my $downloads        = $line->[ $offsets->{downloads} ];
                my $download_revenue = $line->[ $offsets->{download_revenue} ];
                my $streams          = $line->[ $offsets->{streams} ];
                my $stream_revenue   = $line->[ $offsets->{stream_revenue} ];
                my $free_units       = $line->[ $offsets->{free} ];
                my $label_percent    = $line->[ $offsets->{label_percent} ];
                $label_percent =~ s/\D//g;
                $label_percent *= .01;

                $isrc_upc =~ s/\s//g;

                if ( $line->[ $offsets->{isrc_upc} ] =~ /\D/ ) {
                    $product = RPS::File::Sale::TYPE_TRACK;
                } else {
                    $product = RPS::File::Sale::TYPE_ALBUM;
                }

                if ( $isrc_upc && $title && $artist && $downloads =~ /\d+/ && $downloads =~ /\d+/ ) {

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

                    $sale->productType($product);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->isrc($isrc_upc) if ( $product eq RPS::File::Sale::TYPE_TRACK );
                    $sale->upc($isrc_upc)  if ( $product eq RPS::File::Sale::TYPE_ALBUM );
                    $sale->artistName($artist);
                    $sale->trackName($title) if ( $product eq RPS::File::Sale::TYPE_TRACK );
                    $sale->albumName($title) if ( $product eq RPS::File::Sale::TYPE_ALBUM );
                    $sale->labelName($label);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->lineNum($linenum);
                    my $price;

                    # If there are downloads, add this sale
                    if ( $downloads > 0 ) {

                        $sale->formatType(RPS::File::Sale::FORMAT_DOWNLOAD);
                        $sale->units($downloads);
                        $price = $label_percent * ( $download_revenue / $downloads );
                        $price = sprintf( "%.8f", $price );
                        $sale->price($price);
                        $self->_insertSale( sale => $sale );
                    }

                    # If there are streams, add this sale
                    if ( $streams > 0 ) {
                        $sale->formatType(RPS::File::Sale::FORMAT_STREAM);
                        $sale->units($streams);
                        $price = $label_percent * ( $stream_revenue / $streams );
                        $price = sprintf( "%.8f", $price );
                        $sale->price($price);
                        $self->_insertSale( sale => $sale );
                    }

                    # If there are free streams, add this sale
                    if ( $free_units > 0 ) {
                        $sale->formatType(RPS::File::Sale::FORMAT_STREAM);
                        $sale->units($free_units);
                        $sale->free(1);
                        $sale->price(0);
                        $self->_insertSale( sale => $sale );
                    }

                } #else { print STDERR "skip sh: ".$sheet_names->[$sheet_count] . ": l: " . $linenum . " - c:".$country." u:".$units." p:".$price." t:".$title."\n"; }
                $linenum++;
            }
            $sheet_count++;
        } elsif ( ( $sheet_names->[$sheet_count] =~ /consignment/i )
            && ( $version == 2 ) ) {
            $offsets = $fieldMap{'2_consignment'};

            foreach my $line (@$sheet) {
                my $country       = "US";
                my $currency      = "USD";
                my $upc           = $line->[ $offsets->{upc} ];
                my $catalog_title = $line->[ $offsets->{catalog_title} ];
                my $units         = $line->[ $offsets->{units} ];
                my $revenue       = $line->[ $offsets->{revenue} ];
                my $product_type  = RPS::File::Sale::TYPE_ALBUM;
                my $format_type   = RPS::File::Sale::FORMAT_DOWNLOAD;
                my $client_product_id;

                $upc =~ s/\D//g;

                if ( $units == 0 ) {
                    $linenum++;
                    next;
                }

                my $price = $revenue / $units;

                if ( $catalog_title =~ s/^([^ ]+)\s// ) {
                    $client_product_id = $1;
                }

                my ( $artist, $album ) = split( ", ", $catalog_title );

                if ( $upc && $catalog_title && $units =~ /\d+/ && $revenue =~ /\d+/ ) {

                    my $sale = RPS::Import::SaleRec->new();
                    $sale->productType($product_type);
                    $sale->dateBegin($dateBegin);
                    $sale->dateEnd($dateEnd);
                    $sale->upc($upc);
                    $sale->artistName($artist);
                    $sale->albumName($album);
                    $sale->countryCode($country);
                    $sale->currencyCode($currency);
                    $sale->price($price);
                    $sale->units($units);
                    $sale->clientProductID($client_product_id);
                    $sale->formatType($format_type);
                    $sale->lineNum($linenum);
                    $self->_insertSale( sale => $sale );
                }

                $linenum++;

            }

            $sheet_count++;
        }
    }

    return $linenum;
}

#
# Private methods
#

#sub _getDates
#{
#    my ($year,$month,$day,$monthName,$qtr,$passed_date,$dateBegin,$dateEnd);
#	$passed_date = shift;
#    $passed_date =~ s/\s.*$//;
#    if($passed_date =~ m/_(\d\d)_(\d\d)_(\d\d)/) {
#            $year   = $3+2000;
#            $month  = $1;
#            $day    = $2;
#    }
#    if($year && $month && $day) {
#        return ($year."-".sprintf("%02d",$month)."-01",$year."-".sprintf("%02d",$month)."-".sprintf("%02d",$day));
#    }

#    return undef;
#}

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