package BookPub::Import::Importer::Follett::Version6;

use strict;
use Memoize;

use lib '/app/tools/common/lib';
use Common::Util;
use Common::Assert;

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

sub _fieldMap {
    {
        countryCode => 'F',
        rIsbn13     => 'A',
        rTitle      => 'B',
        rAuthor     => 'C',
        rUnits      => 'H',
        rListPrice  => 'G',
        rRevenue    => 'I',
    };
}

sub _unverifiedFieldMap {
    { dateInHeader => 'H2', };
}

sub currencyCode { 'USD' }
sub priceType    { 'agency' }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub _headerIdentifier          { ( rIsbn13 => 'ISBN' ) }
sub _dateNormalization         { 'month' }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateInHeader');
    if ( $date !~ m/^Date: (\d+)\/(\d+)\/(\d\d\d\d)$/ ) {
        $self->fail("Unrecognized date field contents: '$date'");
    }
    return "$3-$1-$2";
}

sub _isSaleRec {
    my $self = shift;
    return if ( $self->rListPrice =~ /Total/i );
    return if ( $self->rIsbn13 =~ /of report/i );
    return $self->SUPER::_isSaleRec();
}

sub rAuthor {
    my $self   = shift;
    my $author = $self->SUPER::rAuthor();
    $author =~ s/^(.+)(, \d{4}-.*)$/$1/;    # First let's get rid of the year after the name
    $author =~ s/^(.+)--\(.*$/$1/;          # Let's also discard the extra name in parentheses.
    $author =~ s/([A-Z]{2,})\./$1/gi;       # Remove periods after any non-initial
    $author =~ s/\,$//;                     # Remove any weird tailing commas
    $author =~ s/^(.*), (.*)$/$2 $1/;       # Then we'll switch it from "last, first." to "first last"
    return $author;
}

sub rSubtitle {
    my $self     = shift;
    my $subtitle = $self->SUPER::rSubtitle;
    $subtitle =~ s/^\-+//;
    return $subtitle;
}

1;
