package BookPub::Import::Importer::CampusEbookstore::v5;

use strict;
use warnings;

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

sub _fieldMap {
    my $self = shift;

    my %map = (
        5 =>{
            dateBegin          => 'A1',
            dateEnd            => 'A1',
            rInstitution       => 'B',
            rIsbn13            => 'D',
            rTitle             => 'E',
            rPurchaseType      => 'E',
            serviceProductID   => 'D',
            rUnits             => 'F',
            rListPrice         => 'G',
            rListPriceCurrency => 'M',
            rDiscount          => 'H',
            rUnitPrice         => 'I',
            rRevenue           => 'L',
            countryCode        => 'M',
            currencyCode       => 'M',
            rDuration          => 'E',
        },
        6 => {
            dateBegin          => 'A1',
            dateEnd            => 'A1',
            rPurchaseType      => 'F',
            purchaseType       => 'F',
            rTitle             => 'F',
            rIsbn13            => 'D',
            rInstitution       => 'B',
            countryCode        => 'N',
            serviceProductID   => 'D',
            rUnits             => 'G',
            rUnitPrice         => 'J',
            rListPrice         => 'H',
            rListPriceCurrency => 'N',
            rDiscount          => 'I',
            rRevenue           => 'M',
            currencyCode       => 'N',
            rDuration          => 'F',
        },
    );

    return $map{$self->version};
}

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

sub dateBegin {
    my $self = shift;

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

    if ($date =~ /SAGE - sales (\w{3}).+? (\d+).+?(\d{4})/i) {
        my ($m, $d, $y) = ($1, $2, $3);
        return sprintf("%04d-%02d-%02d", $y, $months{lc($m)}, $d);
    }
    $self->fail("Cannot determine begin date from: $date");
}

sub dateEnd {
    my $self = shift;

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

    if ($date =~ /SAGE - sales (\w{3}).+?to (\d+), (\d{4})/i) {
        my ($m, $d, $y) = ($1, $2, $3);
        return sprintf("%04d-%02d-%02d", $y, $months{lc($m)}, $d);
    }
    $self->fail("Cannot determine end date from: $date");
}

sub _isSaleRec {
    my $self = shift;

    return ($self->rIsbn13 && $self->rTitle && $self->rUnits && $self->rUnits =~ /\d+$/) ? 1 : 0;
}

1;
