package BookPub::Import::Importer::WebAssign;

use strict;
use warnings;

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

sub _headerIdentifier { ( rTitle => qr/Textbook|\s*SHORT TITLE NAME\s*/ ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            rTitle       => 'B',
            rInstitution => 'A',
            rUnits       => 'C',
            rListPrice   => 'D',
            rRevenue     => 'E',
        },
        3 => {
            rTitle       => 'F',
            rIsbn13      => 'G',
            rInstitution => 'E',
            rUnits       => 'L',
            rUnitPrice   => 'K',
            rRevenue     => 'N',
            rModel       => 'C',
        },
        4 => {
            rTitle          => 'H',
            rIsbn13         => 'I',
            rInstitution    => 'E',
            rState          => 'G',
            rUnits          => 'N',
            rUnitPrice      => 'M',
            rRevenue        => 'P',
            rDeliveryMethod => 'D',
            rModel          => 'C',
        },
        5 => {
            rPurchaseType   => 'D',
            rProductType    => 'L',
            rTitle          => 'H',
            rIsbn13         => 'I',
            rInstitution    => 'E',
            rState          => 'G',
            rUnits          => 'N',
            rUnitPrice      => 'M',
            rRevenue        => 'O',
            rDeliveryMethod => 'D',
            rModel          => 'C',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub _dateNormalization         { 'month' }
sub priceType                  { 'rrp' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType               { BookPub::DB::Item::Sale::kProductTypeEBook }
sub countryCode                { 'US' }
sub currencyCode               { 'USD' }
sub rListPriceCurrency         { 'USD' }
sub rServiceName               { 'WebAssign' }

sub dateBegin { shift->{_dateBegin} }
sub rTitle    { shift->_getByFieldName('rTitle') || '' }

sub purchaseType { shift->rPurchaseType }
sub rPurchaseType {
    my $self = shift;

    if ( $self->version == 5 ) {
        my $type = $self->_getByFieldName('rPurchaseType');
        return $type =~ /^Electronic Subscription$/i
            ? BookPub::DB::Item::Sale::kPurchaseTypeDownload
            : $self->fail("Unable to determine rPurchaseType from '$type'.");
    }

    return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
}


sub _processLine {
    my $self        = shift;
    my $title       = $self->_getByFieldName('rTitle');
    my $institution = $self->_getByFieldName('rInstitution');

    if (   ( $title && $title =~ /Sales Total/i )
        || ( !$title && !$institution ) ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

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

sub isFree {
    my $self = shift;

    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

# we need to get the date from a non-consistent column in the second row.
# I'll get that line and grab the first date-looking item in it, Month 'YY
sub _preProcess {
    my $self = shift;
    my %args  = @_;

    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,
    );

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

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        $sheetnum++;
        my $linenum   = 0;
        my $foundDate = 0;
        foreach my $line (@$sheet) {
            $linenum++;
            if (   $line->[1] =~ /^(\w*) (\d{2,4}) ROYALTY TOTAL$/
                || $line->[3] =~ / (\w*) (\d{2,4})$/ ) {
                $foundDate = 1;
                my $monthName = $1;
                my $day       = 1;
                my $year      = $2;
                if ( length($year) == 2 ) {
                    $year = "20" . $year;
                }
                my $month = $months{ lc($monthName) };
                $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $year, $month, $day );
                return;
            } elsif ( $foundDate == 0 ) {
                next;
            }
        }
    }
}


1;
