package RPS::Import::EMIUK::Physical;

use strict;

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

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

use Data::Dumper;

sub _headerIdentifier { ( totalRevenue => 'NDS Value' ) }

sub currencyCode          { 'GBP' }
sub channel               { RPS::File::Sale::CHANNEL_RETAIL }
sub priceLevel            { RPS::File::Sale::PLEVEL_FULL }

sub productType           {
    my $type = shift->_getByFieldName( 'productType' ) || return;

    if( $type =~ /^cd album$/i ) {
        return RPS::File::Sale::TYPE_CD
    }
    elsif ($type =~ /^vinyl album$/i) {
        return RPS::File::Sale::TYPE_LP;
    }


    die "Unknown product type '$type'";
}

sub physical { 1 }

sub countryCode {
    my $self = shift;
    my $country = $self->SUPER::countryCode() || return;

    $country =~ s/EMI //i;

    my $c = new Common::Country( search => $country =~ /Records UK/ ? 'GB' : $country );

    $self->fail( "Unable to determin country code from '$country'" ) unless( $c->alpha2 );

    return $c->alpha2;
}

sub _processHeader {
    my $self = shift;

    return if( $self->{_dateBegin} );

    my $date = $self->SUPER::_getDateBegin() || return;
    if( $date =~ /\w{3} \d{4}/ ) {
        my $d = new Common::Date($date);
        $self->{_dateBegin} = $d->monthBegin();
        $self->{_dateEnd}   = $d->monthEnd();
    }
}

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

sub _isValidSaleRecord {
    my $self = shift;

    return unless( $self->SUPER::_isValidSaleRecord );

    # There are summary lines in this file that do not have a format set.
    # These need to be ignored.
    return unless( $self->_getByFieldName('productType') );

    # sales file includes lines with 0 sales or 0 returns.  We need to ignore these
    return $self->sales || $self->returns ? 1 : undef;
}

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

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.
###
