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

package RPS::Import::Avarto;

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 RPS::Import::ServiceMap;

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::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';

my %fieldMap = (
        1 => {
            label_name      => 2,
            service_name    => 4,
			start_date      => 5,
            country_code    => 6,
			format_type     => 8,
			service_product_id => 11,
		    upc             => 12,
			isrc            => 14,
			artist          => 17,
			track_name      => 18,
			album_name      => 21,
			units           => 23,
			net_price       => 33,
			currency_code   => 34,
        },
        2 => {
            label_name      => 2,
            service_name    => 4,
            start_date      => 5,
            country_code    => 6,
            format_type     => 8,
            service_product_id => 11,
            upc             => 12,
            isrc            => 14,
            artist          => 17,
            track_name      => 18,
            album_name      => 21,
            units           => 23,
            net_price       => 32,
            currency_code   => 33,
        },        
);

my %gFormatTypeMap = (
    'full track music' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_DOWNLOAD,
        mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'real music' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_RINGTONE,
        mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'ringbacktone' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_RINGTONE,
        mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'video' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_DOWNLOAD, # was FORMAT_VIDEO (FB1324)
        mediaType => RPS::DB::Item::MediaType::kMediaTypeVideo,
    },
);

#public methods

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;

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


            my $country = uc($line->[$offsets->{country_code}]);
            my $currencyCode = uc($line->[$offsets->{currency_code}]);

            my $productType;
            my $format;
            my $mediaType;

            my $mapping = $gFormatTypeMap{ lc($line->[$offsets->{format_type}]) };
            if ($mapping)
            {
                $productType = $mapping->{productType};
                $format = $mapping->{formatType};
                $mediaType = $mapping->{mediaType};
            }

            my $trackTitle = $line->[$offsets->{track_name}];
            my $albumTitle = $line->[$offsets->{album_name}];

            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 $startDate           = $line->[$offsets->{start_date}];
            my $startDate           = $line->[$offsets->{start_date}];
            my $serviceName         = $line->[$offsets->{service_name}];
            my $labelName           = $line->[$offsets->{label_name}];
            my $serviceProductID    = $line->[$offsets->{service_product_id}];


            # Probably wise to allow for blank lines...
            #
            if ($currencyCode || $artist || $albumTitle || $trackTitle)
            {
                $startDate =~ s/\./\//g;

                my ($dateBegin, $dateEnd);
                if ($startDate =~ m/^\d\d\d\d\-\d\d\-\d\d$/) {
                    # Dates with leading year and dashes seem to be ISO 
                    ($dateBegin, $dateEnd) = $self->_getDates(date_begin => $startDate, type => "iso");
                }
                else {
                    # Other dates seem to be euro
                    ($dateBegin, $dateEnd) = $self->_getDates(date_begin => $startDate, type => "eur");
                }

                my $unitPrice = $netPrice / $units;
                
                my $serviceID;
                if ($serviceName)
                {
                    $serviceID = $self->getServiceID(lc ($serviceName)) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $serviceName };

                    if (!$serviceID)
                    {
                        die "Can't find service id for $serviceName\n";    
                    }   
                }             

                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->albumName($albumTitle);
                $sale->artistName($artist);
                $sale->upc($upc);
                $sale->isrc($isrc);
                $sale->units($units);
                $sale->price($unitPrice);
                $sale->countryCode($country);
                $sale->currencyCode($currencyCode);
                $sale->serviceID($serviceID);
                $sale->serviceProductID($serviceProductID);
                $sale->labelName($labelName);
                $sale->lineNum($linenum);

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

	return $linenum;
}



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