#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2013 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package RPS::Import::DashGo::v1;

use strict;

use lib '/app/tools/common/lib';
use Common::Util qw(normalize_date normalize_isrc);
use Common::Assert;

use lib '/app/tools/rps/lib';
use RPS::Import::ServiceMap;


use base 'RPS::Import::Importer';


sub _fieldMap {
    {
        labelName    => 'D',
        serviceID    => 'A',
        artistName   => 'C',
        upc          => 'F',
        isrc         => 'I',
        albumName    => 'E',
        trackName    => 'G',
        units        => 'L',
        price        => 'O',
        countryCode  => 'B',
        currencyCode => 'M',
        productType  => 'N',
    }
}

sub _unverifiedFieldMap {
    {
        distFee        => 'L',
        revenuePayable => 'M',
    }
}

sub _headerIdentifier { ( artistName => 'Artist Name' ) }

my %gFormats = ();

# saleDates - return the start/end date information for the file.
#
sub saleDates {
    my $self = shift;

    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} );

    $self->fail( "Unknown filename" ) unless( $self->filename );

    # We'll look for the pattern "-MM-YY" to determine the sales period
    #
    unless( $self->filename =~ /-(\d{2})-(\d{2})[^\d]/ ) {
        $self->fail( "Could not determine period from filename '" . $self->filename . "'" );
    }

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

    ($self->{_startDate}, $self->{_endDate}) = $self->_getDates( date_begin => $startDate );

    return ($self->{_startDate}, $self->{_endDate});
}

sub units {
    my $self = shift;
    my $units = $self->_getByFieldName('units');
    $units =~ s/\.0$//;
    return $units;
}

sub price {
    my $self = shift;
    my $price = $self->_getByFieldName('price');
    $self->{_revenue} += $price;
    return $price;
}

sub currencyCode {
    my $self = shift;
    my $cc = uc $self->_getByFieldName('currencyCode');
    return substr($cc,0,3);
}

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info( "Starting _preProcess" );
    $self->SUPER::_preProcess(%args);

    # Get the distribution fee and the expected revenue from the footer area
    #
    my $linenum = 0;

    foreach my $line(@{ $args{lines} })
    {
        $self->{line} = $line;

        my $df = $self->_getByFieldName('distFee');

        # Example:   Revenue Payable at(87.0)%:
        #
        if( $df =~ /Revenue Payable at\((\d*\.?\d*)\)%:/i )
        {
            my $n = $1;
            $self->{_distFee} = 100 * (1 - $n/100);

            $self->{_revenuePayable} = $self->_getByFieldName('revenuePayable');

            last;
        }
        $linenum++;
    }
}

sub _postProcess {
    my $self = shift;
    my %args = @_;


    if( exists $self->{_distFee} )
    {
        # Compare the revenue value from the detail lines with the
        # revenue reported in the footer.
        #
        my $expectedRevenue = $self->{_revenuePayable};
        my $totalRevenue    = $self->{_revenue};
        my $discount        = $self->{_distFee};
        my $adjustedRevenue = $totalRevenue - ($discount * $totalRevenue)/100;

        if( abs($expectedRevenue) - abs($adjustedRevenue) >  .01 )
        {
            $self->errstr("Total adjusted revenue $adjustedRevenue does not equal the reported revenue $expectedRevenue");
            return undef;
        }


        # Save the distribution fee information
        #
        my $file = $self->{_file};
        $file->InputDistributionFee(1);
        $file->Save();

        # Iterate over all formats from the file and manually apply
        # the distribution fee to each format.
        #
        foreach my $format ( keys %gFormats )
        {
            $file->CreateUpdateUserInput($file->FileID, 'distribution', $self->{_distFee}, $format);  # apply to each formats
        }
    }
}

sub serviceID {
    my $self = shift;
    my $service = $self->_getByFieldName('serviceID');

    $self->fail( "Service name not defined" ) unless( $service );

    my $serviceID = $self->getServiceID(lc ($service)) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };

    $self->fail( "Unable to determine service id from '$service'" ) unless( $serviceID );

    return $serviceID;
}

sub countryCode
{
    my $self = shift;
    my $countryCode = $self->_getByFieldName('countryCode');

    $countryCode = 'US' if( lc($countryCode) eq '0' || '' eq $countryCode );

    if( $countryCode )
    {
        my $c = new Common::Country( search => $countryCode );
        return $c->alpha2() if( $c );
    }
    return $countryCode;
}

sub _getMappings {
    my $self = shift;
    my $type = $self->_getByFieldName('productType');
    my %mappings = (
        'T' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type => RPS::File::Sale::FORMAT_DOWNLOAD,
            media_type => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'S' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type => RPS::File::Sale::FORMAT_STREAM,
            media_type => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
        'A' => {
            product_type => RPS::File::Sale::TYPE_ALBUM,
            format_type => RPS::File::Sale::FORMAT_DOWNLOAD,
            media_type => RPS::DB::Item::MediaType::kMediaTypeAudio,
        },
    );
    return( $mappings{$type}{product_type},
            $mappings{$type}{format_type},
            $mappings{$type}{media_type} );
}

sub productType {
    my $self = shift;
    my( $productType, $formatType, $mediaType ) = $self->_getMappings();
    return $productType if( $productType );
    $self->fail("Unknown product type");
}

sub formatType {
    my $self = shift;
    my( $productType, $formatType, $mediaType ) = $self->_getMappings();
    $gFormats{$formatType} = 1 if( $formatType );  # keep track of this for later ...
    return $formatType if( $formatType );
    $self->fail("Unknown product type");
}

sub mediaType {
    my $self = shift;
    my( $productType, $formatType, $mediaType ) = $self->_getMappings();
    return $mediaType if( $mediaType );
    $self->fail("Unknown product type");
}

sub isrc {
    my $self = shift;
    my $isrc = $self->_getByFieldName('isrc');
    $isrc = normalize_isrc($isrc);
    return $isrc;
}

sub _isValidSaleRecord {
    my $self = shift;

    return ( defined($self->units) && $self->units != 0 && ($self->trackName || $self->albumName) );
}

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