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

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';

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

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        9 => {

            # Header
            dateBegin => 'A18',

            # Data
            countryCode    => 'A',
            rIsbn13        => 'J',
            rTitle         => 'K',
            rAuthor        => 'M',
            rUnits         => 'O',
            rListPrice     => 'S',
            rPurchasePrice => 'S',
            rDiscount      => 'W',
            rRevenue       => 'X',
        },
        10 => {
            countryCode => 'A',
            rIsbn13     => 'I',
            rTitle      => 'J',
            rAuthor     => 'L',
            rUnits      => 'N',
            rListPrice  => 'S',
            rDiscount   => 'T',
            rUnitPrice  => 'U',
            rRevenue    => 'V',
        },
        11 => {
            countryCode    => 'E',
            rIsbn13        => 'O',
            rTitle         => 'P',
            rAuthor        => 'R',
            rUnits         => 'S',
            rListPrice     => 'X',
            rPurchasePrice => 'W',
            rDiscount      => 'Y',
            rRevenue       => 'AA',
        },
        12 => {
            rAuthor                => 'P',
            rTitle                 => 'N',
            rIsbn13                => 'M',
            countryCode            => 'A',
            rUnits                 => 'R',
            rListPrice             => 'T',
            rListPriceCurrency     => 'S',
            rPurchasePrice         => 'T',
            rPurchasePriceCurrency => 'S',
            rDiscount              => 'X',
            rRevenue               => 'Y',
            currencyCode           => 'S',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        10 => {
            year  => 'A27',
            month => 'A30',
        },
    );
    return $fieldMap{ $self->_version() };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rDistributor               { 'OLF' }
sub currencyCode               { 'GBP' }
sub _dateFormat                { [ 'text', 'numerical', 'iso' ] }
sub _dateNormalization         { 'month' }

sub _getDateBegin {
    my $self      = shift;
    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $year      = $self->_getByFieldName('year');
    my $month     = $self->_getByFieldName('month');

    if ( $year =~ /(\d{4})$/ && $month =~ /(\d{1,2})/ ) {
        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, '1' );
    } elsif ( $dateBegin !~ /(\w+ \d{4})$/ && $self->filename =~ /(\d{1,2}\.\d{4})/ ) {
        $dateBegin = $1;
        $dateBegin =~ s/\./\-/;
    } elsif ( $dateBegin =~ /(\w+ \d{4})$/ ) {
        $dateBegin = $1;
    }

    return $dateBegin;
}

sub _getDateEnd {
    my $self    = shift;
    my $dateEnd = $self->_getDateBegin();

    return $dateEnd;
}

# 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 _isSaleRec {
    my $self = shift;

    # Bail out early on blank rows
    $self->SUPER::_isSaleRec || return 0;

    # OLF added some extra headers in the file, bail if one is detected.
    if ( $self->rUnits =~ /quantity/i ) { return 0; }

    # Required fields or bail
    ( $self->rTitle || $self->rIsbn13 || $self->rAuthor ) || return 0;

    return 1;
}

1;
