package BookPub::Import::Importer::SafariBooks;

use strict;
use warnings;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( isbn => 'eISBN' ) }

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            dateBegin    => 'F5',
            dateEnd      => 'F5',
            isbn         => 'C',
            rTitle       => 'D',
            rAuthor      => 'F',
            rImprint     => 'E',
            rDiscount    => 'J',
            rRevenue     => 'K',
            rChannel     => 'G',
            rListPrice   => 'I',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub countryCode                { 'US' }
sub currencyCode               { 'USD' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeLoan }

sub rListPriceCurrency { 'USD' }
sub priceType          { 'rrp' }

sub _dateFormat        { ['text'] }
sub _dateNormalization { 'month' }

sub rServiceName { 'Safari Books Online' }

sub _getDateBegin {
    my $self = shift;

    if ( !exists $self->{_dateBegin} ) {
        my $dt = $self->_getByFieldName('dateBegin');
        if ( $dt =~ /Statement Period: (\w{3})\w* - (\w{3})\w* (\d{4})/ )    # Statement Period: MMM - MMM YYYY
        {
            $self->{_dateBegin} = "$1-$3";                                   # MMM-YYYY
        }
    }
    return $self->{_dateBegin};
}

sub _getDateEnd {
    my $self = shift;

    if ( !exists $self->{_dateEnd} ) {
        my $dt = $self->_getByFieldName('dateEnd');
        if ( $dt =~ /Statement Period: (\w{3})\w* - (\w{3})\w* (\d{4})/ )    # Statement Period: MMM - MMM YYYY
        {
            $self->{_dateEnd} = "$2-$3";                                     # MMM-YYYY
        }
    }
    return $self->{_dateEnd};
}

sub rUnits {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue') || 0;
    return $revenue >= 0 ? 1 : -1;
}

sub rDiscount {
    my $self = shift;
    my $d    = $self->_getByFieldName('rDiscount');
    return 1 - $d;
}

sub _isSaleRec {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue') || 0;
    my $isbn    = $self->_getByFieldName('isbn')     || '';
    my $title   = $self->_getByFieldName('rTitle')   || '';

    return 0 if $self->rListPrice && $self->rListPrice =~ /Payment Due/i;

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

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


1;
