package BookPub::Import::Importer::EBSCO;

use strict;
use Data::Dumper;

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

sub _headerIdentifier { ( rImprint => 'PUBLISHER NAME' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            dateBegin  => 'A2',
            rIsbn13    => 'D',
            rTitle     => 'B',
            rImprint   => 'A',
            rListPrice => 'E',
            rRevenue   => 'E',
        },
    );

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

sub _useIsSaleRec      { 1 }
sub rServiceName       { 'EBSCO' }
sub _dateNormalization { 'quarter' }
sub _getDateEnd        { shift->{_dateBegin} }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub priceType          { 'rrp' }
sub rDiscount          { 0 }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeLoan }


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

sub _getDateBegin {
    my $self = shift;

    if ( $self->{_dateBegin} ) {
        return $self->{_dateBegin};
    }

    my $date = $self->_getByFieldName('dateBegin');

    if ( $date =~ /(\w+) \d{1,2}, (\d{4})/i ) {
        my $month = $months{ lc($1) };
        my $year  = $2;

        if ($month) {

            # Need to set this to the beginning of the quarter.
            $month = $month - 2;
            $self->{_dateBegin} = $year . "-" . $month . "-01";
            return $self->{_dateBegin};
        }
    }

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

sub countryCode {
    my $self = shift;

    # SAGE only
    if ( Common::RSApp::GetClientID == 365 && $self->rImprint =~ /Sage Publications, Ltd/i ) {
        return 'UK';
    }

    return 'US';
}

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

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

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