#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2009 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------

package RPS::Import::eMusic;

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;
use Common::Assert;
use Common::Log;

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

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

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

my %fieldMap = (
        21 => {
            date_begin       => 1,
            date_end         => 2,
            type             => 3,
            sale_type        => 4,
            label            => 7,
            service_track_id => 8,
            service_album_id => 9,
            track_num        => 11,
            track            => 12,
            artist           => 13,
            upc              => 14,
            isrc             => 15,
            album            => 16,
            country_code     => 17,
            units            => 18,
            net_price        => 25,
            currency_code    => 26,
        },
        22 => { # See Case 12977
            date_begin       => 1,
            date_end         => 2,
            type             => 3,
            sale_type        => 4,
            label            => 7,
            service_track_id => 8,
            service_album_id => 9,
            track_num        => 11,
            track            => 12,
            artist           => 13,
            upc              => 14,
            isrc             => 15,
            album            => 16,
            country_code     => 17,
            units            => 21,
            net_price        => 34,
            currency_code    => 35,
        },
        23 => { # See Case 17245
            date_begin       => 1,
            date_end         => 2,
            user_type        => 3,
            type             => 4,
            sale_type        => 5,
            label            => 8,
            service_track_id => 9,
            service_album_id => 10,
            track_num        => 12,
            track            => 13,
            artist           => 14,
            upc              => 15,
            isrc             => 16,
            album            => 17,
            country_code     => 18,
            units            => 22,
            net_price        => 37,
            currency_code    => 38,
        },
);


#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;

    assert(defined $args{sheets});
    assert(defined $version);

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

    for (my $sheetIndex = 0; $sheetIndex < scalar @{$args{sheets}}; $sheetIndex++)
    {
        my $sheet = $sheets->[$sheetIndex];

        my $foundHeader = 0;
        for (my $lineIndex = 0; $lineIndex < scalar @$sheet; $lineIndex++)
        {
            $linenum = $lineIndex + 1;
            my $line = $sheet->[$lineIndex];


            if (! $foundHeader)
            {
                if ('Start Date' eq $line->[$offsets->{date_begin}])
                {
                    $foundHeader = 1;
                }
                next;
            }


            my $format;
            if ( $version == 21 )
            {
               $format = RPS::File::Sale::FORMAT_VPD;
            }
            elsif( $version == 22 )
            {
               $format = RPS::File::Sale::FORMAT_DOWNLOAD;
            }
            elsif( $version == 23 )  # See FB17521
            {
                my $userType = $line->[$offsets->{user_type}];

                if( $userType =~ /^alc$/i )
                {
                    $format = RPS::File::Sale::FORMAT_DOWNLOAD;
                }
                elsif( $userType =~ /^sub$/i ||
                       $userType eq '' )   # FB17662
                {
                    $format = RPS::File::Sale::FORMAT_VPD;
                }
                else
                {
                    print STDERR "D: unable to determine format from UserType '$userType'\n";
                }
            }

            my $mediaType = RPS::DB::Item::MediaType::kMediaTypeAudio;

            my $productType;
            my $serviceProductID;

            if ($line->[$offsets->{type}] )
            {
                if ($line->[$offsets->{type}] eq 'T')
                {
                    $productType = RPS::File::Sale::TYPE_TRACK;
                    $serviceProductID = $line->[$offsets->{service_track_id}];
                }
                elsif ($line->[$offsets->{type}] eq 'A')
                {
                    $productType = RPS::File::Sale::TYPE_ALBUM;
                    $serviceProductID = $line->[$offsets->{service_album_id}];
                }
                else
                {
                    $self->errstr("Unrecognized product type: ".$line->[$offsets->{type}]);
                    return undef;
                }
            }

            my $saleType            = $line->[$offsets->{sale_type}];
            my $trackNum            = $line->[$offsets->{track_num}];
            my $trackTitle          = $line->[$offsets->{track}];
            my $albumTitle          = $line->[$offsets->{album}];
            my $upc                 = $line->[$offsets->{upc}];
            my $isrc                = $line->[$offsets->{isrc}];
            my $artist              = $line->[$offsets->{artist}];
            my $units               = $line->[$offsets->{units}];
            my $netPrice            = $line->[$offsets->{net_price}];
            my $label               = $line->[$offsets->{label}];
            my $countryCode         = uc($line->[$offsets->{country_code}]);
            my $currencyCode        = uc($line->[$offsets->{currency_code}]);

            #
            if ($units && $artist && ($albumTitle || $trackTitle))
            {
                my ($dateBegin, $dateEnd) = $self->_getDates(date_begin => $line->[$offsets->{date_begin}], date_end => $line->[$offsets->{date_end}]);

                my $unitPrice = $netPrice / $units;

                # If sale type is 'R' (refund) then convert units to negative
                # and make sure price is positive
                if( lc($saleType) eq 'r' )
                {
                    $units *= -1;
                    $unitPrice *= -1 if ( $unitPrice < 1 );
                }

                # If we have positive units with negative revenue, then make sure that
                # the sale is recorded as a return (e.g., make the unit price positive
                # and the units negative). FB1820
                #
                if( $netPrice < 0 && $units > 0 )
                {
                    $unitPrice = abs($unitPrice);
                    $units *= -1;
                }

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

                $sale->mediaType($mediaType);
                $sale->productType($productType);
                $sale->formatType($format);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->labelName($label);
                $sale->trackNum($trackNum);
                $sale->trackName($trackTitle);
                $sale->albumName($albumTitle);
                $sale->artistName($artist);
                $sale->serviceProductID($serviceProductID);
                $sale->upc($upc);
                $sale->isrc($isrc);
                $sale->units($units);
                $sale->price($unitPrice);
                $sale->countryCode($countryCode);
                $sale->currencyCode($currencyCode);
                $sale->lineNum($linenum);

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

	return $linenum;
}



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