package BookPub::Import::Importer::OLF::Version2;

use strict;

use Common::Country;
use BookPub::Tracker::Service;

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer';

sub _headerIdentifier { ( rTitle => 'TITLE' ) }

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

        # Data
        rServiceName => 'C',
        countryCode  => 'A',
        rIsbn13      => 'J',
        rTitle       => 'K',
        rAuthor      => 'M',
        rUnits       => 'N',
        rListPrice   => 'P',
        rDiscount    => 'T',
        rRevenue     => 'V',
    };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rDistributor { 'OLF' }
sub currencyCode { 'GBP' }

sub _isValidSaleRecord {
    my $self = shift;

    return $self->rTitle && ( $self->rIsbn10 || $self->rIsbn13 );
}

sub countryCode {
    my $self = shift;
    my $code = $self->SUPER::countryCode();

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

    return $countryObj->alpha2();
}

sub _processHeader {
    my $self = shift;
    $self->_storeDate();

    if ( $self->_isHeader() && !$self->dateEnd() ) {
        $self->fail("Date not found in header.");
    }
}

sub _storeDate {
    my $self = shift;

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

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

sub _dateFormat { [ 'us', 'iso' ] }
sub _dateNormalization { 'month' }
sub _getDateBegin      { shift->_getDateEnd() }
sub _getDateEnd        { shift->{_dateEnd} }

1;
