package BookPub::Import::Importer::OLF::Version5;

use strict;

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

use lib '/app/tools/bookpub/lib';
use BookPub::Tracker::Service;
use base 'BookPub::Import::Importer::OLF::Base';

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

        # Data
        countryCode => 'A',
        rIsbn13     => 'I',
        rTitle      => 'J',
        rAuthor     => 'L',
        rUnits      => 'P',
        rListPrice  => 'V',
        rDiscount   => 'W',
        rRevenue    => 'Y',
    };
}

sub _unverifiedFieldMap {
    { alternateDateEnd => 'M', };
}

sub currencyCode { 'GBP' }
sub _dateFormat { [ 'eur', 'iso' ] }

sub _storeDate {
    my $self = shift;

    unless ( $self->_getDateEnd() ) {
        my $input = $self->_getByFieldName('dateEnd');

        $self->{_dateEnd} = $input if ( $input && length($input) && $input !~ /[a-zA-Z]/ );
    }

    unless ( $self->_getDateEnd() ) {
        my $input = $self->_getByFieldName('alternateDateEnd');

        if ( $input && length($input) && $input =~ /DATE : (\d+\.\d+\.\d{4})/ ) {
            $self->{_dateEnd} = $1;
        }
    }
}

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

    if ($country) {
        my $countryObj = Common::Country->Get($country) || $self->fail("Unknown country code '$country'");

        # Country is being used as kind of a header, and it's not repeated after the first line,
        # so we'll store it and keep using it until we find a new value.
        $self->{_countryCode} = $countryObj->alpha2();
    }

    if ( $self->{_countryCode} ) {
        return $self->{_countryCode};
    } else {
        $self->fail("Country code not found");
    }
}

1;
