package RPS::Import::PIAS::Physical;

use strict;

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

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

use Data::Dumper;

sub _headerIdentifier { ( albumName => 'TITLE' ) }

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

sub physical { 1 }

sub _processHeader {
    my $self = shift;

    my $label = $self->_getByFieldName('headerLabel');
    my $value = $self->_getByFieldName('headerValue');

    return unless ( $label && $value );

    if ( $label =~ /period/i ) {
        if ( $value =~ /(\w+ \d{4}) - (\w+ \d{4})/ )    # JULY 2015 - DECEMBER 2015
        {
            ( $self->{_dateBegin}, $self->{_dateEnd} ) = $self->_getDates( date_begin => $1, date_end => $2 );
        } else {
            my $d = new Common::Date($value);
            $self->{_dateBegin} = $d->monthBegin();
            $self->{_dateEnd}   = $d->monthEnd();
        }
    }

    if ( $label =~ /currency/i ) {
        ( $self->{_currencyCode} ) = $value =~ /^(\w{3})/i;
    }
}

sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->{_dateEnd} }
sub currencyCode  { shift->{_currencyCode} }

sub productType {
    my $self = shift;

    my $code = $self->_getByFieldName("clientProductID") || "";
    return RPS::File::Sale::TYPE_LP if ($code =~ /LP\w?$/i);
    return RPS::File::Sale::TYPE_CD
}

sub countryCode {
    my $self        = shift;
    my $cname       = $self->_getByFieldName('countryCode');
    my $countryObj  = Common::Country->Get($cname);
    my $countryCode = $countryObj->alpha2() if ($countryObj);
    return $countryCode;
}

sub returns { abs( shift->SUPER::returns ) }

sub _isValidSaleRecord {
    my $self = shift;

    if ( !$self->totalRevenue && ($self->sales || $self->returns) ) {
        $self->fail("Units without revenue are presented.");
    }

    # Look at the line if it has revenue and a track or album name
    #
    return $self->totalRevenue && ( $self->trackName || $self->albumName );

}

# Disable total validation
sub _validateTotalSum       { }
sub _validateSaleTotalSum   { }
sub _validateReturnTotalSum { }
sub _validateReturnsRevenue { }

sub _validateSalesRevenue {
    my ( $self, $saleRec ) = @_;

    my $salesRevenue = $saleRec->salesRevenue;

    if ( !defined $salesRevenue ) {
        die Import::ValidationError->new( $saleRec, "Sales revenue not defined" );
    }

    if ( $salesRevenue !~ /^-?(?:(?:\d+)?\.\d+|\d+(?:\.)?(?:\d+)?)$/ ) {
        die Import::ValidationError->new( $saleRec, "Sales revenue $salesRevenue is in an incorrect format" );
    }
}

###
1;    # Play nicely.
###
