package RPS::Import::OrchardPhysical4;

use strict;
use warnings;

use Date::Calc qw(Days_in_Month);

use lib '/app/tools/common/lib';
use Common::UTF8;
use Common::Country;

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

sub physical { 1 }

sub _fieldMap {
    {
        labelName       => 'I',
        countryCode     => 'D',
        dateBegin       => 'B',
        dateEnd         => 'B',
        productType     => 'L',
        clientProductID => 'G',
        artistName      => 'J',
        upc             => 'E',
        albumName       => 'K',
        currencyCode    => 'AA',
        wholesalePrice  => 'Q',
        sales           => 'T',
        returns         => 'T',
        totalRevenue    => 'X',
        mediaType       => 'L',
    };
}

sub _unverifiedFieldMap {
    {
        _netUnits => 'T',
    };
}

sub _headerIdentifier { upc => 'Orchard UPC' }


sub channel       { RPS::File::Sale::CHANNEL_RETAIL; }
sub priceLevel    { RPS::File::Sale::PLEVEL_UNKNOWN; }

sub saleDates {
    my $self = shift;

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

    # YYYY"M"MM
    if ( my ($year, $month) = $dateBegin =~ /^(\d{4})M(\d{1,2})$/i ) {
        return (
            sprintf( "%04d-%02d-%02d", $year, $month, 1 ),
            sprintf( "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month ) )
        );
    }

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

sub countryCode {
    my $self = shift;

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

    return $oCountry ? $oCountry->alpha2 : undef;
}

sub productType {
    my $self = shift;

    my $type = $self->_getByFieldName('productType') || '';
    if ( $type =~ /^CD$/i ) {
        return RPS::File::Sale::TYPE_CD;
    } elsif ( $type =~ /^12..? Vinyl$/i ) {
        return RPS::File::Sale::TYPE_LP;
    }

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

sub mediaType {
    my $self = shift;

    my $type = $self->_getByFieldName('mediaType') || '';
    if ( $type =~ /^(?:CD|12..? Vinyl)$/i ) {
        return RPS::DB::Item::MediaType::kMediaTypeAudio;
    }

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

# physical
sub netUnits           { $_[0]->_getByFieldName('_netUnits') || 0 }
sub sales              { $_[0]->netUnits     > 0 ? $_[0]->netUnits         : 0 }
sub salesRevenue       { $_[0]->totalRevenue > 0 ? $_[0]->totalRevenue     : 0 }
sub returns            { $_[0]->netUnits     < 0 ? abs $_[0]->netUnits     : 0 }
sub returnsRevenue     { $_[0]->totalRevenue < 0 ? abs $_[0]->totalRevenue : 0 }

sub totalRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName('totalRevenue') || 0;
    $revenue =~ s/,//g;

    return $revenue;
}

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


1;