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

package RPS::Import::Musiwave::TextBase;

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 Client::Service;

use lib '/app/tools/rps/lib';
use RPS::Import::SaleRec;
use RPS::DB::Item::MediaType;
use RPS::File::Sale;

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

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

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

    my $offsets     = $self->_fieldMap;
    my $sheet_names = $args{sheet_names};
    my $sheets      = $args{sheets};
    my $linenum     = 1;

    my $startDate;
    my $endDate;

    # Per Case 14135, the product format should be extracted from the filename
    #
    my $format = _getFormat($fileName);
    if ( !$format ) {
        $self->errstr("Unknown format type in filename ($fileName)");
        return undef;
    }

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

        if ( $sheetIndex == 0 ) {
            ( $startDate, $endDate ) = $self->_getDate( $fileObj->OrigFileName );

            if ( !$startDate ) {
                $self->errstr("Start date not found.");
                return undef;
            }
        }

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

            if ( !$foundHeader ) {
                if ( 'Album Upc' eq $line->[ $offsets->{upc} ] ) {
                    $foundHeader = 1;
                }
                next;
            }

            my $country      = $line->[ $offsets->{country} ];
            my $currencyCode = $line->[ $offsets->{currency} ];

            my $service = $line->[ $offsets->{service} ];
            my $productType;

            #my $format;
            my $mediaType;
            my $artist;

            my $upc           = $line->[ $offsets->{upc} ];
            my $isrc          = $line->[ $offsets->{isrc} ];
            my $netPrice      = $line->[ $offsets->{net_price} ];
            my $numberOfPlays = $line->[ $offsets->{number_of_plays} ];
            my $serviceName   = $line->[ $offsets->{service_name} ];
            my $label         = $line->[ $offsets->{label} ];
            my $serviceID     = $self->getServiceID( lc($serviceName) );

            my $units = 1;
            $netPrice =~ s/,/./g;

            my $mapping = $productTypeMap->{ lc( $line->[ $offsets->{type} ] ) };
            if ($mapping) {

                # Note: per Case 14135, get the format from the filename.
                # E.g., don't use the format defined in $mapping->{formatType}
                #
                $productType = $mapping->{productType};
                $mediaType   = $mapping->{mediaType};

                if ($numberOfPlays) {
                    $units = $numberOfPlays;
                }

            }

            my $artist;
            my $trackTitle;
            my $albumTitle;

            if ( $productType eq RPS::File::Sale::TYPE_TRACK ) {
                $artist     = $line->[ $offsets->{track_artist} ];
                $trackTitle = $line->[ $offsets->{track_name} ];
                $albumTitle = $line->[ $offsets->{album_name} ];
            } else {
                $artist     = $line->[ $offsets->{track_artist} ];
                $albumTitle = $line->[ $offsets->{track_name} ];
            }

            my $serviceProductID = $line->[ $offsets->{track_product_id} ] if ( defined( $offsets->{track_product_id} ) );

            # Probably wise to allow for blank lines...
            #
            if ( defined($units) && ( $trackTitle || $albumTitle ) ) {
                unless ($format) {
                    $self->errstr("Unknown product type ($line->[$offsets->{type}]). Line: $linenum");
                    return undef;
                }

                # net_price is zero for streaming records.  This test sanity checks
                # to ensure this is a streaming file.
                #
                if (   $netPrice == 0
                    && !$numberOfPlays
                    && $format ne RPS::File::Sale::FORMAT_STREAM ) {
                    $self->errstr("Net price can only be 0 in stream files");
                    return undef;
                }

                my ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $startDate, date_end => $endDate );

                my $unitPrice = $netPrice / $units;

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

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

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

    return $linenum;
}

sub _getFormat {
    my ($f) = @_;

    my $format;

    return if ( !$f );

    if ( $f =~ m/dto_/i ) {
        $format = RPS::File::Sale::FORMAT_DOWNLOAD;
    } elsif ( $f =~ m/redeemed_/i ) {
        $format = RPS::File::Sale::FORMAT_DOWNLOAD;
    } elsif ( $f =~ m/stream_/i || $f =~ m/streamazp_/i || $f =~ m/streaming_/i ) {
        $format = RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $f =~ m/playcount_/i ) {
        $format = RPS::File::Sale::FORMAT_STREAM;
    } elsif ( $f =~ m/subscription_/i ) {
        $format = RPS::File::Sale::FORMAT_STREAM;
    }
    return $format;
}

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