package RPS::Import::PIASDigital::v3;

use strict;
use warnings;

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

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

use base qw/RPS::Import::MapFaceBase RPS::Import::Importer/;

use Date::Calc qw(Days_in_Month Decode_Month);

sub _headerIdentifier { ( upc => 'Barcode' ) }

sub _fieldMap {
    {
        # Header
        dateBegin        => 'F',
        currencyCode     => 'B',

        # Detail
        serviceID        => 'H',
        countryCode      => 'E',

        formatType       => 'G',
        productType      => 'F',

        artistName       => 'A',
        upc              => 'D',
        isrc             => 'C',
        albumName        => 'B',
        trackName        => 'B',
        units            => 'I',
        price            => 'O',
    }
}

sub _unverifiedFieldMap {
    {
        dms            => 'H',
        _grossRevenue  => 'J',
        _mechDeduction => 'K',
        _fee           => 'M',
    }
}

sub mediaType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || '';
    return $type =~ /^DIGITAL VIDEO SHORT FORM$/i
        ? RPS::DB::Item::MediaType::kMediaTypeVideo
        : RPS::DB::Item::MediaType::kMediaTypeAudio;
    return $self->handleError( "Unknown media_type: '$type'", RPS::DB::Item::SaleImportError::kErrorMediaType );
}

sub currencyCode {
    my $self = shift;
    return( $self->{_currencyCode} ) if( $self->{_currencyCode} );
    $self->fail("Unable to read currency code from header");
}

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

    my %countryMap = (
       'kazakstan' => 'kazakhstan',
    );

    $name = $countryMap{lc $name} || $name;

    my $o = Common::Country->Get( $name );
    if( $o )
    {
        return $o->alpha2;
    }
    $self->handleError( "Unknown country: '$name'.", RPS::DB::Item::SaleImportError::kErrorCountry );
}

sub saleDates {
    my $self = shift;
    return ($self->{_startDate}, $self->{_endDate}) if( $self->{_startDate} ); # from header; see _preProcess
}

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

    # we already have another mapping for this string in the ServiceMap.pm, so we'are looking for this string here.
    return Client::Service::DSP_TIM_MUSIC if $name =~ /^Soundaymusic - timmusic$/i;
    return Client::Service::DSP_TENCENT   if $name =~ /\(Tencent\)/i;
    return Client::Service::DSP_XIAMI     if $name =~ /^Xiami/i;

    my $serviceID = $self->getServiceID( $name ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $name };
    $serviceID = Client::Service::DSP_GROOVESHARK if( !$serviceID && $name =~ /^grooveshark\(settlement\)$/i );
    $serviceID = Client::Service::DSP_LIMEWIRE if( !$serviceID && $name =~ /^limewire\(settlement\)$/i );
    $serviceID = Client::Service::DSP_24_7_MUSICSHOP if( !$serviceID && ( $name =~ /^24\/7 MUSICSHOP/i ));
    $serviceID = Client::Service::DSP_AMAZON_MUSIC_UNLIMITED if( !$serviceID && ( $name =~ /Amazon Unlimited/i ));

    return $serviceID if( $serviceID );

    return $self->handleError( "Unknown service: '$name'", RPS::DB::Item::SaleImportError::kErrorService );
}

sub albumName  {
    my $self = shift;
    my $name = $self->_getByFieldName('albumName');
    return ( $self->productType eq RPS::File::Sale::TYPE_ALBUM ) ? $name : "";
}

sub trackName  {
    my $self = shift;
    my $name = $self->_getByFieldName('trackName');
    return ( $self->productType eq RPS::File::Sale::TYPE_TRACK ) ? $name : "";
}

sub isrc  {
    my $self = shift;
    my $isrc = $self->_getByFieldName('isrc');
    $isrc =~ s/-//g;
    return ( $self->productType eq RPS::File::Sale::TYPE_TRACK ) ? $isrc : "";
}

sub formatType  {
    my $self = shift;
    my $fmt = $self->_getByFieldName('formatType');
    my $dms = $self->_getByFieldName('dms');

    if( $fmt =~ /^a la carte download product$/i )
    {
        return RPS::File::Sale::FORMAT_DOWNLOAD;
    }
    elsif( $fmt =~ /^radio streaming product$/i ||
           $fmt =~ /^(?:Breakage|Cloud Streaming|Discount subsc' streaming product|Radio streaming product|Streaming)$/i ||
           $fmt =~ /^discount subsc' streaming product$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }
    elsif( $fmt =~ /^settlement$/i )
    {
        if( $dms =~ /^grooveshark\(settlement\)$/i )
        {
            return RPS::File::Sale::FORMAT_STREAM;
        }
        elsif( $dms =~ /^limewire\(settlement\)$/i )
        {
            return RPS::File::Sale::FORMAT_VPD; # FB265
        }
        else
        {
            return $self->handleError( "Unable to determine format type from price category: '$fmt', dms($dms)", RPS::DB::Item::SaleImportError::kErrorFormatType );
        }
    }
    elsif( $fmt =~ /^subscr' stream prod\(teth\)$/i ||
           $fmt =~ /^subscription dl product$/i ||
           $fmt =~ /^a la carte download product$/i )
    {
        return RPS::File::Sale::FORMAT_TETHERED;
    }
    elsif( $fmt =~ /^official ad-funded streaming product$/i ||
           $fmt =~ /^subscr' streaming product$/i            ||
           $fmt =~ /^subsc' stream prod \(a\)$/i             ||
           $fmt =~ /^Subsc' UGC product$/i                   ||
           $fmt =~ /^ugc ad-funded streaming product$/i      ||
           $fmt =~ /^cloud streaming$/i                      ||
           $fmt =~ /^breakage$/i                             ||
           $fmt =~ /^streaming$/i )
    {
        return RPS::File::Sale::FORMAT_STREAM;
    }

    return $self->handleError( "Unable to determine format type from price category: '$fmt'", RPS::DB::Item::SaleImportError::kErrorFormatType );

}

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || '';
    if ( $type =~ /^(?:(?:digital )?track|DIGITAL VIDEO SHORT FORM)$/i ) {
        return RPS::File::Sale::TYPE_TRACK;
    } elsif ( $type =~ /^digital (?:album|single|ep|Album AV Bundle)$/i ) {
        return RPS::File::Sale::TYPE_ALBUM;
    }

    $self->handleError( "Unknown product type: '$type'", RPS::DB::Item::SaleImportError::kErrorNonqualifying );
}

sub price {
    my $self = shift;

    my $price = $self->_getByFieldName('price') || 0;
    unless ($price) {
        my $lineNum = $self->linenum;
        # L = J - K
        my $grossRevenue  = $self->_getByFieldName('_grossRevenue') || 0;
        my $mechDeduction = $self->_getByFieldName('_mechDeduction') || 0;
        my $netRevenue = $grossRevenue - $mechDeduction;
        # N = J * ( M / 100 )
        my $fee = $self->_getByFieldName('_fee') || 0;
        my $totalFee = $grossRevenue * ( $fee / 100 );

        $price = $netRevenue - $totalFee;
    }

    return $price;
}
sub units {
    my $self = shift;

    my $price = $self->price() || 0;
    my $units = $self->_getByFieldName('units') || 0;

    if ( $price > 0 ) {
         $units = $units ? abs($units) : 1;
    } elsif ( $price < 0 ) {
        $units = $units ? -1 * abs($units) : -1;
    }

    return $units;
}

sub unitPrice { abs( shift->SUPER::unitPrice ) }

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

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

    foreach my $line(@{ $args{lines} }) {

        $self->{line} = $line;

        # Get the date from the header
        #
        if( !$self->{_startDate} && $self->_getByFieldName('dateBegin') =~ /for period (\w+) (\d{4})/i )
        {
            my $month = Decode_Month($1);
            my $year  = $2;

            $self->{_startDate} = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
            $self->{_endDate}   = sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month($year, $month) );
        }

        # Look for the currency code information
        #
        if( !$self->{_currencyCode} && $self->_getByFieldName('artistName') =~ /currency:/i )
        {
            my $ccode = $self->_getByFieldName('currencyCode');
            if( $ccode =~ /^(\w{3})/ )
            {
                $self->{_currencyCode} = $1;
            }
        }

    }
}

sub _isValidSaleRecord {

    return ( $_[0]->_getByFieldName('artistName') || $_[0]->_getByFieldName('albumName') )
    && ($_[0]->units || $_[0]->price);
}

# mapFace
sub _mapFaceProductType { 'productType' }
sub _mapFaceServiceID   { 'serviceID' }
sub _mapFaceCountryCode { 'countryCode' }
sub _mapFaceFormatType  { 'formatType' }
sub _mapFaceMediaType   { 'mediaType' }

1;
