package RPS::Import::Revelator::v1;

use strict;
use warnings;

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

use base 'RPS::Import::Importer';

sub _fieldMap {
    {
        labelName    => 'E',
        countryCode  => 'D',
        dateBegin    => 'B',
        dateEnd      => 'B',
        productType  => 'M',
        formatType   => 'N',
        artistName   => 'F',
        upc          => 'K',
        albumName    => 'G',
        isrc         => 'L',
        trackName    => 'H',
        units        => 'O',
        currencyCode => 'R1',
        free         => 'N',
        price        => 'R',
    };
}

sub _headerIdentifier { upc => 'UPC' }

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

sub saleDates {
    my $self  = shift;

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

    $self->fail( "Could not determine date from '$date'." );
}

sub currencyCode {
    my $self = shift;

    my $codeStr = $self->_getByFieldName('currencyCode') || '';
    my ($code) = $codeStr =~ /.*([a-z]{3})$/i;

    return $code;
}

sub countryCode {
    my $self = shift;

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

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

sub productType {
    my $self = shift;

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

    $self->fail("Could not parse product type from '$type'");
}

sub formatType {
    my $self = shift;

    my $type = $self->_getByFieldName('formatType') || '';
    return RPS::File::Sale::FORMAT_STREAM   if $type =~ /^(?:(?:Ad-Supported|Subscription) Streaming|Unmonetized)$/i;
    return RPS::File::Sale::FORMAT_DOWNLOAD if $type =~ /^Download$/i;

    $self->fail("Could not determine format type from '$type'.");
}

sub free {
    my $self = shift;

    my $type  = $self->_getByFieldName('formatType') || '';
    my $price = $self->price();

    return $type =~ /^Unmonetized$/i && !$price ? 1 : 0;
}

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;
}


1;
