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

use strict;
use Date::Calc qw(Add_Delta_Days);

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 {
    {
        # header
        dateBegin => 'C',

        # data
        rIsbn13    => 'D',
        rTitle     => 'C',
        rAuthor    => 'B',
        rUnits     => 'F',
        rListPrice => 'E',
        rRevenue   => 'G',
    };
}

sub _useIsSaleRec { 1 }

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

sub _headerIdentifier { ( rIsbn13 => 'ISBN' ) }

sub _dateNormalization { 'month' }

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;
    my $linenum  = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        # We need to grab the row 2, col C value to get the date
        foreach my $line (@$sheet) {

            $linenum++;

            if ( $line->[2] =~ m/For (\w+) (\d{4})$/ ) {
                my $date = new Common::Date("$1 $2");
                $self->{_dateBegin} = "$date";
                return;
            } else {
                next;
            }
        }
    }
}

sub _isSaleRec {
    my $self = shift;
    return if ( $self->rUnits =~ /Total/i );
    return if ( $self->rAuthor =~ /of report/i );

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

sub _getDateBegin { shift->{_dateBegin} }

sub rAuthor {
    my $self   = shift;
    my $author = $self->SUPER::rAuthor();

    # First let's get rid of the year after the name
    if ( $author =~ /^(.+)(, \d{4}-.*)$/ ) {
        $author = $1;
    }

    # Let's also discard the extra name in parentheses.
    if ( $author =~ /^(.+)--\(/ ) {
        $author = $1;
    }

    # Then we'll switch it from "last, first" to "first last"
    if ( $author =~ /^([\w\s]+), ([\w\s]+)[\.,]*$/ ) {
        $author = $2 . " " . $1;
    }

    return $author;
}

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $title;
}

sub rSubtitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $subtitle;
}

###
1;    # Play nicely.
###
