package BookPub::Import::Importer::LanguageWorld;

use strict;

use Data::Dumper;
use Date::Simple;

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

sub _fieldMap {
    my $self     = shift;
    my %fieldMap = (
        1 => {
            dateBegin    => 'B3',
            dateEnd      => 'B3',
            rAuthor      => 'C',
            rTitle       => 'B',
            rIsbn13      => 'D',
            countryCode  => 'J',
            rUnits       => 'I',
            rUnitPrice   => 'H',
            rListPrice   => 'F',
            rDiscount    => 'G',
            rRevenue     => 'K',
            currencyCode => 'K6',
        },
    );

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

sub _headerIdentifier { ( rIsbn13 => 'eISBN' ) }
sub _useIsSaleRec { 1 }
sub _autoParseTitleAndSubtitle { 1 }

sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType          { 'rrp' }
sub rListPriceCurrency { shift->currencyCode() }

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

    if ( $date =~ /From: (\d{4}-\d{2}-\d{2})\s+To: \d{4}-\d{2}-\d{2}/i ) {
        $date = $1;
    }

    return $date;
}

sub _getDateEnd {
    my $self = shift;
    my $date = $self->_getByFieldName('dateEnd');

    if ( $date =~ /From: \d{4}-\d{2}-\d{2}\s+To: (\d{4}-\d{2}-\d{2})/i ) {
        $date = $1;
    }

    return $date;
}

sub currencyCode {
    my $self = shift;
    my $code = $self->_getByFieldName('currencyCode');

    if ( $code =~ /Royalties Due \((\w{3})\)/i ) {
        $code = $1;
    }

    return $code;
}

sub isFree {
    my $self = shift;

    my $isFree    = "N";
    my $revenue   = $self->_getByFieldName('rRevenue');
    my $listPrice = $self->_getByFieldName('rListPrice');

    if ( $revenue == 0 && $listPrice == 0 ) {
        $isFree = "Y";
    }

    return $isFree;
}

sub _isSaleRec {
    my $self      = shift;
    my $title     = $self->_getByFieldName('rTitle');
    my $author    = $self->_getByFieldName('rAuthor');
    my $isbn      = $self->_getByFieldName('rIsbn13');
    my $unitPrice = $self->_getByFieldName('rUnitPrice');
    my $country   = $self->_getByFieldName('countryCode');

    # Skipping the subtotal line at the end.
    if ( !$title && !$author && !$isbn && !$unitPrice && !$country ) {
        return undef;
    }

    return $self->SUPER::_isSaleRec();
}

1;
