package BookPub::Import::Importer::VitalSource::Version2;

use strict;

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

sub _fieldMap {
    {
        countryCode => 'D',
        rPostalCode => 'C',
        dateBegin   => 'A3',
        rIsbn13     => 'F',
        rTitle      => 'E',
        rUnits      => 'H',
        rListPrice  => 'I',
        rDiscount   => 'J',
        rRevenue    => 'M',
    };
}

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

my %months = (
    JAN => 1,
    FEB => 2,
    MAR => 3,
    APR => 4,
    MAY => 5,
    JUN => 6,
    JUL => 7,
    AUG => 8,
    SEP => 9,
    OCT => 10,
    NOV => 11,
    DEC => 12,
);

# trim all non-digit characters from isbn
sub rIsbn13 {
    my $self = shift;
    my $value = $self->_getByFieldName('rIsbn13') || return;
    my $isbn;

    if ( $value =~ m/(\d{13})/ ) {
        $isbn = $1;
    }
    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, $day, $year );

    # extract month name, day, year
    # DD-MMM-YY (23-JAN-14)
    if ( $date =~ /(\d{2})-(\w{3})-(\d{2})/ ) {
        $day   = $1;
        $month = $months{$2};
        $year  = 2000 + $3;
    } elsif ( $date =~ / (\w+) (\d{1,2}) through \w+ \d{1,2}, (\d{4})/ ) {
        $day   = $2;
        $month = $months{ uc( substr( $1, 0, 3 ) ) };
        $year  = $3;
    } else {
        $self->fail("Unexpected date format: $date");
    }

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

    return $date;
}

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

    # extract month name, day, year
    # DD-MMM-YY (23-JAN-14)
    if ( $date =~ /and (\d{2})-(\w{3})-(\d{2})/ ) {
        $day   = $1;
        $month = $months{$2};
        $year  = 2000 + $3;
    } elsif ( $date =~ / \w+ \d{1,2} through (\w+) (\d{1,2}), (\d{4})/ ) {
        $day   = $2;
        $month = $months{ uc( substr( $1, 0, 3 ) ) };
        $year  = $3;
    } else {
        $self->fail("Unexpected date format: $date");
    }

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

    return $date;
}

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