package RPS::Import::AppleMusic::v4;

use strict;
use warnings;

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


sub _fieldMap {
    my $self = shift;

    my %map = (
        4 => {
            countryCode      => 'A',
            dateBegin        => 'B1',
            dateEnd          => 'B2',
            serviceProductID => 'B',
            artistName       => 'F',
            isrc             => 'C',
            trackName        => 'E',
            units            => 'L',
            currencyCode     => 'N',
            price            => 'M',
        },
        5 => {
            countryCode      => 'A',
            dateBegin        => 'B1',
            dateEnd          => 'B2',
            serviceProductID => 'B',
            artistName       => 'F',
            isrc             => 'C',
            trackName        => 'E',
            units            => 'L',
            currencyCode     => 'B4',
            price            => 'M',
        },
    );

    return $map{ $self->_version };
}

sub _headerIdentifier { isrc => 'ISRC' }

sub serviceID   { Client::Service::DSP_APPLE_MUSIC }
sub productType { RPS::File::Sale::TYPE_TRACK }
sub formatType  { RPS::File::Sale::FORMAT_STREAM }
sub mediaType   { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub countryCode {
    my $self = shift;

    my $country = $self->_getByFieldName('countryCode') || '';
    my $oCountry = Common::Country->Get($country);
    return $oCountry->alpha2 if $oCountry;

    $self->fail("Unable to determine country  code from: '$country'");
}

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';
    # mm.dd.yyyy
    if ( $date =~ /^(\d{1,2}).(\d{1,2}).(\d{4})$/ ) {
        return sprintf "%04d-%02d-%02d", $3, $1, $2;
    }

    $self->fail("Unable to determine date begin from: '$date '");
}

sub dateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || '';
    # mm.dd.yyyy
    if ( $date =~ /^(\d{1,2}).(\d{1,2}).(\d{4})$/ ) {
        return sprintf "%04d-%02d-%02d", $3, $1, $2;
    }

    $self->fail("Unable to determine date end from: '$date '");
}

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

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

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

    return $units;
}

sub _isValidSaleRecord {
    my $self = shift;

    return 1 if ($self->units || $self->price) && $self->currencyCode;

    return 0;
}


1;
