package RPS::Import::Yandex::v1;

use strict;
use warnings;

use lib '/app/tools/rps/lib';
use RPS::Import::ServiceMap;
use Date::Calc qw(Days_in_Month);

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

sub physical { 2 }

sub _fieldMapExtended {
    {
        digital => {
            option1 => {
                labelName    => 'E',
                serviceID    => 'A',
                countryCode  => 'L',
                dateBegin    => 'B',
                dateEnd      => 'C',
                productType  => 'K',
                formatType   => 'N',
                artistName   => 'H',
                upc          => 'J',
                albumName    => 'G',
                isrc         => 'K',
                trackName    => 'I',
                units        => 'O',
                price        => 'P',
                currencyCode => 'P1',
            },
         },
    };
}

sub _unverifiedFieldMapExtended { {} }

sub _headerIdentifierExtended {
    {
        digital => {
            option1 => {
                upc => 'Release_ID',
            },
        },
    };
}

sub currencyCode {
    my $self = shift;

    my $code = $self->_getByFieldName('currencyCode') || '';
    return $code =~ /_(\w{3})$/;
}

#sub countryCode {
#    my $self = shift;
#
#    my $name = $self->_getByFieldName('countryCode') || '';
#    return 'US' if $name =~ /^USA$/i;
#
#    my $country = Common::Country->Get($name);
#    return $country ? $country->alpha2 : undef ;
#}

sub saleDates {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin') || '';
    if (my ($m, $y) = $dateBegin =~ /^(\d\d)\.\d\d\.(\d{4}$)/) {
        $dateBegin = sprintf( "%04d-%02d-%02d", $y, $m, 1);

        my $dateEnd = sprintf( "%04d-%02d-%02d", $y, $m, Days_in_Month( $y, $m));

        return ($dateBegin, $dateEnd);
    }

    $self->fail("Can't determine sales date from '$dateBegin'.");
}

sub productType {
    my $self = shift;

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

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

sub formatType {
    my $self = shift;

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

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

sub mediaType {
    return RPS::DB::Item::MediaType::kMediaTypeAudio;
}

sub units {
    my $self = shift;

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

    # check if the value of units is undefined or blank
    $self->fail("The value of units is not defined.") if !$units;

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

    return $units;
}

sub _isValidSaleRecord {
    return ( $_[0]->_getByFieldName('units') || $_[0]->_getByFieldName('price') )
}


1;
