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

package RPS::Import::Bleep;

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 qw(%COUNTRY_TO_CODE);
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::Import::Importer;
use base 'RPS::Import::Importer';

my %fieldMap = (
    1 => {
        date         => 0,
        label        => 1,
        artist       => 2,
        album_name   => 3,
        track_name   => 3,    # yes, same column for album and track name - use product_type to determine
        catalog_id   => 4,
        upc          => 5,
        isrc         => 6,
        product_type => 7,
        unit_price   => 9,    # They give us this, but we'll be using net_price (as is our usual practice).
        units        => 10,
        net_price    => 11,
    },
);

my %gProductTypeMap = (
    'track'            => RPS::File::Sale::TYPE_TRACK(),
    'complete release' => RPS::File::Sale::TYPE_ALBUM(),
);

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

    # Data is on the sheet named 'AllData'
    #
    for ( my $sheetIndex = 0 ; $sheetIndex < scalar @{ $args{sheets} } ; $sheetIndex++ ) {
        next unless $sheet_names->[$sheetIndex] eq 'AllData';
        my $sheet = $sheets->[$sheetIndex];

        # start at 1 - skipping the header.
        #
        for ( my $lineIndex = 1 ; $lineIndex < scalar @$sheet ; $lineIndex++ ) {
            $linenum = $lineIndex + 1;
            my $line = $sheet->[$lineIndex];

            my $country      = 'GB';
            my $currencyCode = 'GBP';

            my $productType = $gProductTypeMap{ lc( $line->[ $offsets->{product_type} ] ) };

            my $trackTitle;
            my $albumTitle;

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

            my $format    = RPS::File::Sale::FORMAT_DOWNLOAD;
            my $upc       = $line->[ $offsets->{upc} ];
            my $isrc      = $line->[ $offsets->{isrc} ];
            my $artist    = $line->[ $offsets->{artist} ];
            my $catalogID = $line->[ $offsets->{catalog_id} ];

            my $units     = $line->[ $offsets->{units} ];
            my $netPrice  = $line->[ $offsets->{net_price} ];
            my $unitPrice = $netPrice / $units;

            # Since this file provides the 'per-sale price', let's make sure
            # it all sums up.
            #
            my $checkPrice = $line->[ $offsets->{unit_price} ];

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

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

                die "Error on line $linenum - Could not determine product type from '" . $line->[ $offsets->{product_type} ] . "'"
                  unless $productType;

                die "Error on line $linenum - PayoutPerSale of $checkPrice does not match calculated unit price of $unitPrice"
                  unless ( $unitPrice == $checkPrice );

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

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

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

    return $linenum;
}

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