package RPS::Import::Merlin::v13;

use strict;

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

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

use Data::Dumper;
use Date::Calc qw(Days_in_Month Decode_Month);

sub _fieldMap {
    {
        # header
        currencyCode => 'D',
        dateBegin    => 'A',

        # detail
        albumName   => 'G',
        artistName  => 'E',
        countryCode => 'B',
        formatType  => 'O',
        isrc        => 'C',
        price       => 'L',
        trackName   => 'F',
        serviceID   => 'A',
        units       => 'J',
        upc         => 'D',
    };
}

sub _unverifiedFieldMap {
    {
        # footer
        distFee => 'M',
    };
}

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

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

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

sub serviceID {
    my $self       = shift;
    my $service    = $self->_getByFieldName('serviceID');
    my $_serviceID = $self->getServiceID( lc($service) ) || $RPS::Import::ServiceMap::SERVICE_ALIASES{ lc $service };
    if ($_serviceID) {
        return $self->{_serviceID};
    }
    $self->fail("Unknown service '$service'");
}

sub saleDates {
    my $self = shift;
    return ( $self->{_startDate}, $self->{_endDate} ) if ( $self->{_startDate} );    # from header; see _preProcess
}

sub currencyCode {
    my $self = shift;
    return $self->{_currencyCode} if ( $self->{_currencyCode} );                     # from header; see _preProcess
}

sub formatType {
    my $self = shift;
    my $type = $self->_getByFieldName('formatType');

    if ( $type =~ /^(premium|plus|basic-stream|basic-cached|on\-demand|pre\-configured|subscriber\-normal)$/i ) {
        return RPS::File::Sale::FORMAT_STREAM;
    } else {
        $self->fail("Could not determine format from $type");
    }
}

# Return 1 if distribution fee is optional.  By default, the
# fee must be present in the sales file.
#
sub distFeeOptional { 0 }

sub price {
    my $self = shift;

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

    # If the distribution fee isn't optional, then it must be present in
    # the sales file and we'll factor it into the revenue here.
    #
    # Otherwise, you will have to enable the dist fee option in the tracker page
    # XSLT (see raptor/templates/tracker.xsl) and override distFeeOptional()
    # such that it returns 1 for the appropriate importer version.  The end-user
    # will then have to manually input the dist fee via the tracker page.
    #
    if ( !$self->distFeeOptional ) {
        $self->fail("Unable to determine distribution fee") unless ( $self->{_distFee} );

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

    return $price;
}

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

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

    my $distFee;

    my $getDateFlag;        # set if we find a date header
    my $getCurrencyFlag;    # set if we find a currency header

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

        $self->{line} = $line;

        # Get the date from the header
        #
        if ( !$getDateFlag && $self->_getByFieldName('dateBegin') =~ /accounted period/i ) {
            $getDateFlag = 1;
        } elsif ( !$self->{_startDate} && $getDateFlag ) {
            my $dt = $self->_getByFieldName('dateBegin');

            if ( $dt =~ /^(\d{4}) (\d{2})$/ )    # YYYY MM
            {
                $self->{_startDate} = sprintf( "%04d-%02d-%02d", $1, $2, 1 );

                $self->{_endDate} = sprintf( "%04d-%02d-%02d", $1, $2, Days_in_Month( $1, $2 ) )

            } else {
                print STDERR "_preProcess: WARNING: Unable to decode date '$dt'\n";
                $self->errstr("Unable to decode date '$dt' in header");
                return undef;
            }
        }

        # Get the country from the header
        #
        if ( !$getCurrencyFlag && $self->_getByFieldName('currencyCode') =~ /Currency/i ) {
            $getCurrencyFlag = 1;
        } elsif ( !$self->{_currencyCode} && $getCurrencyFlag ) {
            $self->{_currencyCode} = $self->_getByFieldName('currencyCode');
        }

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

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

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