package BookPub::Import::Importer::AlexanderStreet;

use strict;
use Data::Dumper;

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

sub _headerIdentifier { ( rIsbn13 => 'IP Identifier' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rIsbn13      => 'C',
            rTitle       => 'D',
            rAdjustments => 'N',
            rDiscount    => 'K',
            rRevenue     => 'O',
            rDuration    => 'F',
            rModel       => 'E',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub _getDateBegin              { shift->{_dateBegin} }
sub _getDateEnd                { shift->{_dateBegin} }
sub _dateNormalization         { 'month' }
sub countryCode                { 'US' }
sub currencyCode               { 'USD' }
sub priceType                  { 'rrp' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeStream }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName( service_id => shift->serviceID );
}

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

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

    my $filename = $self->filename;
    if ( $filename =~ m/(\d{4})[\s_](\d{1,2})/i ) {
        my $year  = $1;
        my $month = $2;
        my $day   = 1;
        $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }

    # Didn't find it?  Give up.
    if ( !$self->{_dateBegin} ) {
        $self->errstr('Unable to find date in filename');
        return undef;
    }

}

sub units {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

    if ( $revenue < 0 ) {
        return -1;
    } else {
        return 1;
    }
}

sub _isSaleRec {
    my $self     = shift;
    my $title    = $self->_getByFieldName('rTitle');
    my $isbn     = $self->_getByFieldName('rIsbn13');
    my $discount = $self->_getByFieldName('rDiscount');
    my $duration = $self->_getByFieldName('rDuration');
    my $model    = $self->_getByFieldName('rModel');

    # Skipping the subtotal lines, which are blank are in these columns.
    if ( !$title && !$isbn && !$discount && !$duration && !$model ) {
        return undef;
    }

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

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