package BookPub::Import::Importer::VitalSource::Version9;

use strict;

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

sub _fieldMap {
    {
        dateBegin  => 'A3',
        rIsbn13    => 'C',
        rTitle     => 'B',
        rUnits     => 'E',
        rListPrice => 'F',
        rUnitPrice => 'G',
        rRevenue   => 'H',
    };
}

sub _unverifiedFieldMap {
    { alternateIsbn => 'D', };
}

sub _headerIdentifier { ( rRevenue => 'Total' ) }
sub _autoParseTitleAndSubtitle { 1 }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceType                  { 'rrp' }
sub rListPriceCurrency         { 'USD' }
sub currencyCode               { 'USD' }
sub countryCode                { 'US' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _useIsSaleRec              { 1 }

# trim all non-digit characters from isbn
sub rIsbn13 {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13');
    if ( !$isbn ) {
        $isbn = $self->_getByFieldName('alternateIsbn');
    }

    $isbn =~ s/-//g;

    return $isbn;
}

sub _isSaleRec {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $isbn      = $self->_getByFieldName('rIsbn13');
    my $title     = $self->_getByFieldName('rTitle');

    # We're going to skip the subtotal lines, which are blank for these fields
    if ( ( !$dateBegin && !$isbn && !$title ) || ( $dateBegin == '' && $isbn == '' && $title == '' ) ) {
        return 0;
    }

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

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;
    my ( $month, $year );

    if ( $date =~ / (\d{1,2}), (\d{4})$/ ) {
        $month = $1;
        $year  = $2;
    } else {
        $self->fail("Unexpected date format: $date");
    }

    $date = sprintf( "%04d-%02d-%02d", $year, $month, 1 );

    return $date;
}

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