package BookPub::Import::Importer::MBSTextbookExchange::v1;

use strict;
use warnings;

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rServiceName     => 'A',
            dateBegin        => 'Q',
            dateEnd          => 'Q',
            rAuthor          => 'L',
            rTitle           => 'M',
            rIsbn10          => 'V',
            rIsbn13          => 'W',
            rInstitution     => 'C',
            rState           => 'I',
            rPostalCode      => 'J',
            serviceProductID => 'K',
            rUnits           => 'O',
            rUnitPrice       => 'P',
            rListPrice       => 'N',
            rRevenue         => 'T',
            rDistributor     => 'A',
        },
    );

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

sub _headerIdentifier { rTitle => 'Title' }

sub _useIsSaleRec      { 1 }
sub priceType          { 'rrp' }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeEBook }


sub rServiceName {
    my $self = shift;

    my $service = $self->_getByFieldName('rServiceName') || '';

    return 'MBS Textbook Exchange' if $service =~ /MBSTEX/i;

    $self->fail("Unknown service name: '$service'");
}

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';
    if ( my ($m, $d, $y) = $date =~ /(\d{1,2})\/(\d{1,2})\/(\d{4})/ ) {
        return sprintf "%04d-%02d-%02d", $y, $m, $d;
    }
    if ( my ($y, $m, $d) = $date =~ /(\d{4})[-](\d{1,2})[-](\d{1,2})/ ) {
        return sprintf "%04d-%02d-%02d", $y, $m, $d;
    }

    $self->fail("Unable to determine date begin from: '$date'");
}

sub dateEnd { shift->dateBegin }

sub isFree {
    my $self = shift;

    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

sub _isSaleRec {
    my $self = shift;

    my $rListPrice = $self->_getByFieldName('rListPrice') || '';
    return if $rListPrice =~ /Total/i;

    my $rUnits = $self->_getByFieldName('rUnits')     || '';
    my $rRevenue = $self->_getByFieldName('rRevenue') || '';
    return if (!$rUnits && !$rRevenue);

    return 1;
}


1;
