package BookPub::Import::Importer::OLF::Version8;

use strict;

use lib '/app/tools/bookpub/lib';
use lib '/app/tools/common/lib';

use Date::Calc qw(Add_Delta_YM);

use base 'BookPub::Import::Importer::OLF::Base';

sub _fieldMap {
    {
        # Header
        dateEnd => 'O',

        # Data
        countryCode    => 'D',
        rIsbn13        => 'L',
        rTitle         => 'M',
        rAuthor        => 'Q',
        rUnits         => 'S',
        rListPrice     => 'X',
        rPurchasePrice => 'W',
        rDiscount      => 'Y',
        rRevenue       => 'AA',
    };
}

sub currencyCode           { 'GBP' }
sub rListPriceCurrency     { shift->currencyCode }
sub rPurchasePriceCurrency { shift->currencyCode }
sub _dateFormat            { [ 'eur', 'iso' ] }

# we're going to try to be a little clever about price type
# as this importer was requested as agency even though all
# the others are rrp. obviously 'nothing' in the file tells
# us, so we'll look at the discount.
sub priceType {
    my $self = shift;

    my $priceType = 'rrp';
    if ( $self->rDiscount() < .40 ) {
        $priceType = 'agency';
    }

    return $priceType;
}

# need to kick the date back a month when we finally find it
sub _storeDate {
    my $self = shift;

    if ( !defined( $self->{_dateEnd} ) ) {
        my $date = $self->_getByFieldName('dateEnd');

        if ( $date && $date =~ /(\d{4})[-\/](\d{2})[-\/](\d{2})/ ) {
            my ( $year, $month, $day ) = Add_Delta_YM( $1, $2, $3, 0, -1 );

            $self->{_dateEnd} = sprintf( '%04d-%02d-%02d', $year, $month, $day );
        }
    }
}

# The sales file is a little odd.  The data comes in country blocks.  The first line of the
# data has the country and also the line after the last line of the block.  So when we find
# a country, we stuff it into $self->{_country} and use that value for all the lines with
# a blank country.  When we get a new country, we use that one.

sub countryCode {
    my $self    = shift;
    my $country = $self->_getByFieldName('countryCode');

    if ( length($country) == 0 ) {
        $country = $self->{_country};
    }

    if ( length($country) > 0 ) {
        $self->{_country} = $country;
    }

    my $countryObj = Common::Country->Get($country) || $self->fail("Unknown country '$country'");
    return $countryObj->alpha2();
}

sub rTaxUnitPrice {
    my $self = shift;

    return $self->rPurchasePrice - $self->rListPrice;
}

1;
