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

package RPS::Import::CreateSpaceDigital;

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::File::Sale;
use RPS::DB::Item::MediaType;

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

my %fieldMap = (
    2 => {
        date               => 0,
        service_product_id => 1,
        title              => 2,
        units              => 3,
        product_type       => 5,
        net_sales          => 6,
    },

);

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

    my $currencyCode = "USD";
    my $countryCode  = "US";
    my $format       = RPS::File::Sale::FORMAT_DOWNLOAD;
    my $mediaType    = RPS::DB::Item::MediaType::kMediaTypeAudio;

    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 ( 'Date' eq $line->[ $offsets->{date} ] ) {
                    $foundHeader = 1;
                }
                next;
            }

            my $productType;
            my $trackTitle;
            my $trackNum;
            my $albumTitle;

            if ( $line->[ $offsets->{product_type} ] eq 'Amazon MP3 Track Download' ) {
                $productType = RPS::File::Sale::TYPE_TRACK;
                my $titleData = $line->[ $offsets->{title} ];

                # Example of data in this field:
                # Everything, Everything (Live) (Track 8 - Rez/Cowgirl)
                # We want to grab everything in the parentheses after "Track # -" for the track name
                # And pretty much everything before that for the album title.
                # May as well grab the track num while we're doing this.

                $titleData =~ m/^(.*)\(Track (\d+) - (.*)\)/;

                $albumTitle = $1;
                $trackNum   = $2;
                $trackTitle = $3;
            } elsif ( $line->[ $offsets->{product_type} ] eq 'Amazon MP3 Album Download' ) {
                $productType = RPS::File::Sale::TYPE_ALBUM;
                $albumTitle  = $line->[ $offsets->{title} ];
            }

            # This was erroring out on blank lines, so let's make sure there is something there before we complain.
            #
            elsif ( $line->[ $offsets->{product_type} ] ) {
                $self->errstr( "Line $linenum - Unrecognized product type: " . $line->[ $offsets->{product_type} ] );
                return undef;
            }

            my $serviceProductID = $line->[ $offsets->{service_product_id} ];
            my $units            = $line->[ $offsets->{units} ];
            my $netSales         = $line->[ $offsets->{net_sales} ];
            $netSales =~ s/\$//;

            #print STDERR "line num: $linenum units: $units net sales: $netSales album title: $albumTitle track title: $trackTitle\n";

            # Probably wise to allow for blank lines...
            #
            if ( $units && $netSales && ( $albumTitle || $trackTitle ) ) {
                my ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $line->[ $offsets->{date} ] );

                my $unitPrice = $netSales / $units;

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

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

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

    return $linenum;
}

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