package RPS::Import::Merlin::v53;

use strict;
use warnings;

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

sub _fieldMap {
    {
        labelName    => 'L',
        countryCode  => 'M',
        dateBegin    => 'B',
        dateEnd      => 'C',
        productType  => 'O',
        formatType   => 'P',
        artistName   => 'H',
        upc          => 'D',
        albumName    => 'J',
        isrc         => 'F',
        trackName    => 'I',
        units        => 'R',
        currencyCode => 'U',
        price        => 'U',
    };
}

sub _headerIdentifier { isrc => 'ISRC' }

sub serviceID { Client::Service::DSP_GOOGLE }
sub mediaType { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub countryCode {
    my $self = shift;

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

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

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || '';
    return RPS::File::Sale::TYPE_TRACK if $type =~ /^TRACK$/i;

    $self->fail("Unable to determine productType from '$type'.");
}

sub formatType {
    my $self = shift;

    my $type = $self->_getByFieldName('formatType') || '';
    return RPS::File::Sale::FORMAT_STREAM if $type =~ /^PLAY$/i;

    $self->fail("Unable to determine formatType from '$type'.");
}

sub units {
    my $self = shift;

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

    $price =~ s/[^0-9\.]//g;
    $units =~ s/[^0-9]//g;

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

    return $units;
}

sub currencyCode { shift->{_currency_code} }

sub _processHeader {
    my ($self, %args) = @_;

    my $currencyCode = $self->_getByFieldName('currencyCode') || '';
    ( $self->{_currency_code} ) = $currencyCode =~ /^([a-z]{3})_/i;

    return 1;
}

sub _isValidSaleRecord {
    my $self = shift;

    $self->fail("The line doesn't contain catalog information.") if !$self->isrc && !$self->upc;

    return  $self->units && defined $self->price && ($self->artistName || $self->albumName);
}


1;