package RPS::Import::RightsUp::v1;

use strict;
use warnings;

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

use parent 'RPS::Import::ImporterMixed';
use Date::Calc qw(Add_Delta_Days Days_in_Month);

sub physical { 0 }

sub _fieldMapExtended {
    {
        digital => {
            option1 => {
                labelName   => 'B',
                countryCode => 'H',
                dateBegin   => 'M',
                dateEnd     => 'N',
                artistName  => 'D',
                isrc        => 'F',
                trackName   => 'E',
                price       => 'J',
            },
        },
    };
}

sub _unverifiedFieldMapExtended { {} }

sub _headerIdentifierExtended {
    {
        digital => {
            option1 => {
                isrc => 'Isrc',
            },
        },
    };
}

sub currencyCode { "EUR" }
sub serviceID    { Client::Service::DSP_RIGHTS_UP }
sub productType  { RPS::File::Sale::TYPE_TRACK }
sub formatType   { RPS::File::Sale::FORMAT_PERFORMANCE }
sub mediaType    { RPS::DB::Item::MediaType::kMediaTypeAudio }

sub saleDates {
    my $self = shift;

    my $db = $self->_getByFieldName('dateBegin') || '';
    my $de = $self->_getByFieldName('dateEnd')   || '';
    my ($startDate, $endDate);

    if ( $db =~ /^(\d{4})-(\d{1,2})/ ) {   # YYYY-MM
        my ( $year, $month) = ( $1, $2 );
        $startDate = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
    }
    if ( $de =~ /^(\d{4})-(\d{1,2})-(\d{1,2})$/ ) {   # YYYY-MM-DD
        my ( $year, $month, $day ) = ( $1, $2, $3 );
        $endDate = sprintf( "%04d-%02d-%02d", $year, $month, $day );
	}

    return ( $startDate, $endDate );
}

sub countryCode {
    my $self    = shift;

    my $country = $self->_getByFieldName('countryCode') || '';

    return 'CI' if $country =~ /^Africa$/i;

    my $oCountry = Common::Country->new( search => $country );
    return $oCountry->alpha2() if $oCountry;

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

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

    my $units = 0;
    my $price = sprintf "%.8f", ($self->_getByFieldName('price') || 0);

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

    return $units;
}

sub _isValidSaleRecord {
    my $self = shift;

    return $self->units || $self->price;
}


1;
