package RPS::Import::DDEX::v1;

use strict;

use lib '/app/tools/common/lib';
use Common::Date;

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

use Data::Dumper;

sub _headerIdentifier { ( ddexVersion => '2009/dsr-flat/10' ) }

sub _fieldMap {
    {
        countryCode      => 'Q',
        dateBegin        => 'B',
        productType      => 'P',
        formatType       => 'M',
        artistName       => 'F',
        upc              => 'C',
        albumName        => 'D',
        isrc             => 'C',
        trackName        => 'E',
        units            => 'G',
        currencyCode     => 'I',
        price            => 'K',
        mediaType        => 'P',
    }
}

sub _unverifiedFieldMap {{
        returns         => 'H',
        ddexVersion     => 'A',
        unitTotal       => 'G',
        revenueTotal    => 'N',
}}

my $ourUnitTotal;
my $ourRevenueTotal;

sub _processHeader {
    my $self = shift;

    my $unitTotal = $self->_getByFieldName('unitTotal') || return;        
    $self->{_unitTotal} = $unitTotal;
    
    my $revenueTotal = $self->_getByFieldName('revenueTotal') || return;        
    $self->{_revenueTotal} = $revenueTotal;    
}

sub productType {
    my $self = shift;
    my $productType = $self->_getByFieldName('productType') || return;

    if( lc $productType eq 'trackrelease' ) {
        return RPS::File::Sale::TYPE_TRACK;
    } elsif ( lc $productType eq 'album' ) {
        return RPS::File::Sale::TYPE_ALBUM;
    }
    
    $self->fail( "Unknown product type '$productType'" );
}

sub formatType  {
    my $self = shift;
    my $format = $self->_getByFieldName('formatType') || return;

    if( lc $format eq 'ondemandstream' || lc $format eq 'noninteractivestream' ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } elsif( lc $format eq 'conditionaldownload' ) {
        return RPS::File::Sale::FORMAT_TETHERED;
    } elsif( lc $format eq 'permanentdownload' ) {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }

    $self->fail( "Unknown format type '$format'" );
}

sub mediaType {
    my $self = shift;
    my $mediaType = $self->_getByFieldName('mediaType') || return;

    if( lc $mediaType eq 'trackrelease' ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    } elsif ( lc $mediaType eq 'album' ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }

    $self->fail( "Unknown media type '$mediaType'" );
}

sub units  {
    my $self = shift;
    my $grossUnits = $self->_getByFieldName('units') || return;
    my $returns = $self->_getByFieldName('returns');
    
    my $netUnits = $grossUnits - $returns;
    $ourUnitTotal += $netUnits;
    
    return $netUnits;
}

sub upc  {
    my $self = shift;
    my $upc;
    my $upcField = $self->_getByFieldName('upc') || return;
    my @fieldArray = split(',', $upcField);
    foreach my $field (@fieldArray)
    {
        if ($field =~ /UPC:(\d+)/i)
        {
            $upc = $1;
            last;
        }
    }
    return $upc;
}

sub isrc  {
    my $self = shift;
    my $isrc;
    my $isrcField = $self->_getByFieldName('isrc') || return;
    my @fieldArray = split(',', $isrcField);
    foreach my $field (@fieldArray)
    {
        if ($field =~ /ISRC:(\w+)/i)
        {
            $isrc = $1;
            last;
        }
    }
    return $isrc;
}

sub unitPrice {
    my $self = shift;
    my $price = $self->_getByFieldName('price') || return;
    
    my $grossUnits = $self->_getByFieldName('units');
    my $returns = $self->_getByFieldName('returns');
    my $netUnits = $grossUnits - $returns;    
    
    $ourRevenueTotal += $netUnits * $price;
    
    return $price;
}


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

	Log->info( "Starting _postProcess" );
    $self->SUPER::_postProcess(%args);   
    
    # Let's make sure out totals match the totals in the file.
    # Units are being added to the running total twice, so we need to compensate for that.
    $ourUnitTotal /= 2;
    my $theirUnitTotal = $self->{_unitTotal};
    if ($ourUnitTotal != $theirUnitTotal)
    {
        print STDERR "Unit total does not match total in file ($ourUnitTotal != $theirUnitTotal)\n";
        $self->errstr("Unit total does not match total in file ($ourUnitTotal != $theirUnitTotal)");
        return undef;    
    }
    
    my $theirRevenueTotal = $self->{_revenueTotal};
    # Need to round our total to be consistent with the file total format.
    $ourRevenueTotal = sprintf("%.2f", $ourRevenueTotal);
    # allow a 2 cent variance
    if ( abs($ourRevenueTotal - $theirRevenueTotal) >= 0.02 )
    {
        print STDERR "Revenue total does not match total in file ($ourRevenueTotal != $theirRevenueTotal)\n";
        $self->errstr("Revenue total does not match total in file ($ourRevenueTotal != $theirRevenueTotal)");
        return undef;            
    }    
}


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