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

package RPS::Import::MobileStreams2;

use strict;

use Date::Calc qw(Days_in_Month Add_Delta_Days Decode_Month);

use lib '/app/tools/rps/lib';
use RPS::Import::SaleRec;
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 RPS::File::Sale;
use RPS::Import::ServiceMap;

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

my %fieldMap = (
        2 => {
            currency_code   => 7,
            start_date      => 0,
            format_type     => 4,
            artist          => 2,
            track_name      => 3,
            units           => 6,
            net_price       => 9,
        },
        3 => {
            currency_code   => 10,
            start_date      => 0,
            format_type     => 6,
            artist          => 4,
            track_name      => 5,
            units           => 9,
            net_price       => 12,
            isrc            => 3,
        },
        4 => {
            currency_code   => 14, # O
            start_date      => 0,  # A
            format_type     => 9,  # J
            artist          => 7,  # H
            track_name      => 8,  # I
            units           => 13, # N
            net_price       => 17, # R
            isrc            => 6,  # G
            service_name    => 10, # K
            territory       => 12, # M
        },
        5 => {
            currency_code   => 11, # L
            start_date      => 0,  # A
            format_type     => 6,  # G
            artist          => 4,  # E
            track_name      => 5,  # F
            units           => 10, # K
            net_price       => 14, # O
            #isrc            => ,  # 
            service_name    => 7,  # H
            territory       => 9,  # J
        },
);

my %gFormatTypeMap = (
    'tt' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_RINGTONE,
        mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
    'rbt' =>
    {
        productType => RPS::File::Sale::TYPE_TRACK,
        formatType => RPS::File::Sale::FORMAT_RINGBACK,
        mediaType => RPS::DB::Item::MediaType::kMediaTypeAudio,
    },
);

#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;
		$linenum = 1;
		for (my $lineIndex = 0; $lineIndex < scalar @$sheet; $lineIndex++)
        {
            $linenum = $lineIndex + 1;
            my $line = $sheet->[$lineIndex];


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

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

            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 $artist              = $line->[$offsets->{artist}];
            my $units               = $line->[$offsets->{units}];
            my $netPrice            = $line->[$offsets->{net_price}];
            my $fStartDate          = $line->[$offsets->{start_date}];
			$fStartDate =~ /(\d{4})(\d{2})/;

			my $startDate = sprintf( "%04d-%02d-%02d", $1, $2, '01' );

            my $isrc                = $line->[$offsets->{isrc}] if ( $offsets->{isrc} );
            my $upc                 = $line->[$offsets->{upc}]  if ( $offsets->{upc} );

            my $serviceID;
            if( exists $offsets->{service_name} )
            {
                my $serviceName = $line->[$offsets->{service_name}];
                if( $serviceName && '' ne $serviceName )
                {
                    $serviceID = $self->getServiceID(lc ($serviceName)) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $serviceName };
                    unless( $serviceID )
                    {
                        $self->errstr("couldn't get service from $serviceName on line $linenum");
                        return undef;
                    }
                }
            }


            # Probably wise to allow for blank lines...
            #
            if ($units || $trackTitle)
            {
                if( exists $offsets->{territory} )
                {
                    $countryCode = $line->[$offsets->{territory}];
                }
                else
                {
    			    if( lc($currencyCode) eq 'gbp' ) {
				        $countryCode = 'GB';
			        } elsif( lc($currencyCode) eq 'usd' ) {
    				    $countryCode = 'US';
			        } else {
                        die "Could not set country code from currency code '$currencyCode' (line no: $linenum)";
			        }
			    }

                $startDate =~ s/\./\//g;
				my ($dateBegin, $dateEnd) = $self->_getDates(date_begin => $startDate);

                my $unitPrice = $netPrice / $units;

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

                $sale->serviceID($serviceID) if( $serviceID );
                $sale->mediaType($mediaType);
                $sale->productType($productType);
                $sale->formatType($format);
                $sale->dateBegin($dateBegin);
                $sale->dateEnd($dateEnd);
                $sale->trackName($trackTitle);
                $sale->artistName($artist);
                $sale->units($units);
                $sale->price($unitPrice);
                $sale->currencyCode($currencyCode);
                $sale->countryCode($countryCode);
                $sale->lineNum($linenum);

                $sale->isrc($isrc) if ( defined $offsets->{isrc} && "" ne $isrc );
                $sale->upc($upc) if ( defined $offsets->{upc} && "" ne $upc );

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

	return $linenum;
}



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