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

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',
        rPostalCode  => 'E',
        dateBegin    => 'I1',
        rIsbn13      => 'A',
        rTitle       => 'B',
        rAuthor      => 'C',
        rUnits       => 'H',
        rListPrice   => 'G',
        rDiscount    => 'I',
        rRevenue     => 'J',
        rInstitution => 'D',
    };
}

sub currencyCode         { 'USD' }
sub rListPriceCurrency   { 'USD' }
sub priceType            { 'rrp' }
sub productType          { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType         { shift->productType(); }
sub purchaseType         { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceTypeQualifierID { BookPub::DB::Item::PriceTypeQualifier::kSchoolLibrary }
sub rServiceName         { 'Follett' }

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

my %months = (
    january   => 1,
    february  => 2,
    march     => 3,
    april     => 4,
    may       => 5,
    june      => 6,
    july      => 7,
    august    => 8,
    september => 9,
    october   => 10,
    november  => 11,
    december  => 12,
);

sub dateBegin {
    my $self = shift;

    if ( $self->filename =~ /(\w+) (\d{4})/ ) {
        my ($year, $month)  = ($2, lc($1));
        return sprintf( "%04d-%02d-%02d", $year, $months{$month}, 1 );
    }

    $self->fail("Unexpected date format");
}

sub _isSaleRec {
    my $self = shift;
    return if ( $self->sheetname() =~ /Sheet1/i );
    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;
