package RPS::Import::Merlin::v14;

use strict;

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

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

use Data::Dumper;

sub _headerIdentifier { ( upc => 'UPC' ) }

sub _fieldMap {
    {
        # Detail
        dateBegin    => 'A',
        dateEnd      => 'B',
        labelName    => 'G',
        countryCode  => 'E',
        currencyCode => 'N',
        artistName   => 'H',
        upc          => 'K',
        isrc         => 'L',
        trackName    => 'I',
        units        => 'M',
        price        => 'R',
    };
}

sub _unverifiedFieldMap {
    {
        # Footer
        distFee => 'S',
    };
}

sub productType { return RPS::File::Sale::TYPE_TRACK; }

sub formatType { return RPS::File::Sale::FORMAT_STREAM; }

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

sub price {
    my $self = shift;

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

    $self->fail("Unable to determine distribution fee") unless ( $self->{_distFee} );

    my $distFee = $self->{_distFee};
    $distFee = ( 100 - $distFee ) * .01;
    $price *= $distFee;

    return $price;
}

sub countryCode {
    my $self = shift;

    my $countryName = $self->_getByFieldName('countryCode');
    my $o           = Common::Country->Get($countryName);

    return $o->alpha2() if ($o);

    $self->errstr("Unknown country '$countryName'");
}

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    my $distFee;

    foreach my $line ( @{ $args{lines} } ) {

        $self->{line} = $line;

        # Get the distribution fee from the footer
        #
        $distFee = $self->_getByFieldName('distFee');

        if ( $distFee =~ /LESS Merlin ADMIN FEE \((.+?)%\)/ ) {
            $self->{_distFee} = $1;
            last;
        }
    }
}

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