package RPS::Import::Universal::v68;

use strict;
use warnings;

use lib '/app/tools/rps/lib';
use RPS::File::Sale;
use RPS::Import::ServiceMap;
use RPS::DB::Item::MediaType;

use parent 'RPS::Import::MapFaceBase';
use parent 'RPS::Import::ImporterMixed';

sub physical { 2 }

sub _fieldMapExtended {
    {
        mixed => {
            option1 => {
                countryCode  => 'F',
                dateBegin    => 'G',
                dateEnd      => 'H',
                artistName   => 'C',
                upc          => 'B',
                albumName    => 'D',
                isrc         => 'B',
                trackName    => 'D',
                units        => 'J',
                channel      => 'I',
                totalRevenue => 'Q',
                price        => 'Q',
                mediaType    => 'W',
                currencyCode => 'T',
            },
        },
    };
}

sub _unverifiedFieldMapExtended {
    {
        mixed => {
            option1 => {
                _configuration => 'E',
                _sales_channel => 'I',
                netUnits => "J"
            },
        }
    };
}

sub _headerIdentifierExtended {
    {
        mixed => {
            option1 => { upc => 'Int. Catalogue Number' }
        },
    };
}

my %productMap = (
    '52-E CD SINGLE' => {
        '31-PERMANENT DOWNLOAD' => {
            product_type => RPS::File::Sale::TYPE_ALBUM,
            format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
        }
    },
    '56-CD ALBUM' => {
        '31-PERMANENT DOWNLOAD' => {
            product_type => RPS::File::Sale::TYPE_ALBUM,
            format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
        },
        '11-RETAILER' => {
            product_type => RPS::File::Sale::TYPE_CD
        },
        '19-THIRD PARTY MULTI ARTIST' => {
            product_type => RPS::File::Sale::TYPE_CD
        },
    },
    'ID-ELECTRONIC TRACK AUDIO' => {
        '31-PERMANENT DOWNLOAD' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
        },
        '38-STREAMING' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_STREAM
        },
        'CS-CLOUD SERVICE' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_STREAM
        },
        'SC-SUBSCRIPTION STREAMING' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_STREAM
        },
        'XS-DIGITAL ALLOCATIONS (STR' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_STREAM
        },
        'XD-DIGITAL ALLOCATIONS (DOW' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_DOWNLOAD
        },

    },
    'IV-ELECTRONIC TRACK VIDEO' => {
        '38-STREAMING' => {
            product_type => RPS::File::Sale::TYPE_TRACK,
            format_type  => RPS::File::Sale::FORMAT_STREAM
        }
    }

);

sub currencyCode { 
    my $self = shift;

    my $currency_code = $self->_getByFieldName('currencyCode') || '';

    return 'EUR' if ($currency_code == 997);

    $self->fail("Currency code is not specified. Line: " . $self->linenum);
}

sub priceLevel   { RPS::File::Sale::PLEVEL_UNKNOWN }

sub serviceID { return Client::Service::DSP_UNIVERSAL }

sub countryCode   {
    my $self = shift;

    my $name = $self->_getByFieldName('countryCode') || '';
    $name =~ s/^\d+-//g;

    my $country = Common::Country->Get($name);

    return $country ? $country->alpha2() : $name;
}

sub saleDates {
    my $self = shift;

    my $sdate = $self->_getByFieldName('dateBegin') || '';
    my $edate = $self->_getByFieldName('dateEnd') || '';

    if ($sdate =~ /^(\d{4})(\d{2})(\d{2})$/) {
        $sdate = sprintf( "%04d-%02d-%02d", $1, $2, $3);
    }

    if ($edate =~ /^(\d{4})(\d{2})(\d{2})$/) {
        $edate = sprintf( "%04d-%02d-%02d", $1, $2, $3);
    }

    return ( $sdate, $edate );
}

sub productType {
    my $self = shift;

    my $configuration = uc( $self->_getByFieldName('_configuration') || '' );
    my $channel = uc( $self->_getByFieldName('_sales_channel') || '' ); 

    if ( exists $productMap{$configuration} && exists $productMap{$configuration}->{$channel} && exists $productMap{$configuration}->{$channel}->{product_type} ) {
        return $productMap{$configuration}->{$channel}->{product_type};
    }

    return $self->handleError(
        "Product type not set: $configuration",
        RPS::DB::Item::SaleImportError::kErrorNonqualifying
    );
}

sub formatType {
    my $self = shift;
    
    my $configuration = uc( $self->_getByFieldName('_configuration') || '' );
    my $channel = uc( $self->_getByFieldName('_sales_channel') || '' ); 
    
    if ( exists $productMap{$configuration} && exists $productMap{$configuration}->{$channel} && exists $productMap{$configuration}->{$channel}->{format_type} ) {
        return $productMap{$configuration}->{$channel}->{format_type};
    }

    return $self->handleError(
        "Couldn't determine product format '$configuration': ",
        RPS::DB::Item::SaleImportError::kErrorFormatType
    );
}

sub upc {
    my $self = shift;

    my $isDigitalProduct = $self->isDigitalProduct( $self->productType );
    return !$isDigitalProduct || $self->productType eq RPS::File::Sale::TYPE_ALBUM
        ? $self->_getByFieldName('upc')
        : undef;
}

sub isrc {
    my $self = shift;

    return $self->productType eq RPS::File::Sale::TYPE_TRACK ? $self->_getByFieldName('isrc') : undef;
}

sub albumName {
    my $self = shift;

    return ($self->productType eq RPS::File::Sale::TYPE_ALBUM || $self->productType eq RPS::File::Sale::TYPE_CD)
        ? $self->_getByFieldName('albumName')
        : undef;
}

sub trackName {
    my $self = shift;

    return $self->productType eq RPS::File::Sale::TYPE_TRACK
        ? $self->_getByFieldName('trackName')
        : undef;
}

sub channel {
    my $self = shift;

    my $isDigitalProduct = $self->isDigitalProduct( $self->productType );
    my $channel = $self->_getByFieldName('channel') || '';
    if (!$isDigitalProduct && $channel =~ /^19-THIRD PARTY MULTI ARTIST|11-RETAILER$/i) {
        return RPS::File::Sale::CHANNEL_RETAIL;
    }

    $self->fail("Unsupported sales channel for physical product type: '$channel'.");
}

sub mediaType {
    my $self = shift;

    my $type = uc( $self->_getByFieldName('mediaType') || '' );
    return RPS::DB::Item::MediaType::kMediaTypeAudio if (!$type || ($type eq "A"));
    return RPS::DB::Item::MediaType::kMediaTypeVideo if ($type eq "V");


    return $self->handleError(
        "Media type not set: '$type'",
        RPS::DB::Item::SaleImportError::kErrorNonqualifying
    );
}


sub price     { abs( shift->_getByFieldName('price') || 0 ) }
sub units {
    my $self = shift;

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

    return $price < 0 ? abs($units) * -1 : $units;
}
sub unitPrice { abs shift->SUPER::unitPrice }

sub netUnits       { sprintf "%.0f", ( shift->_getByFieldName('netUnits') || 0 ) }
sub totalRevenue   { $_[0]->_getByFieldName('totalRevenue')               || 0 }
sub sales          { $_[0]->netUnits     > 0 ? $_[0]->netUnits         : 0 }
sub salesRevenue   { $_[0]->totalRevenue > 0 ? $_[0]->totalRevenue     : 0 }
sub returns        { $_[0]->netUnits     < 0 ? abs $_[0]->netUnits     : 0 }
sub returnsRevenue { $_[0]->totalRevenue < 0 ? abs $_[0]->totalRevenue : 0 }

sub _isValidSaleRecord {
    my $self = shift;

    return $self->netUnits && defined $self->totalRevenue && $self->_getByFieldName('albumName');
}

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

1;
