package BookPub::Import::Importer::Odilo::Version6;

use strict;
use warnings;

use Common::UTF8;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::PriceTypeQualifier;
use parent 'BookPub::Import::Importer';

sub _fieldMap {
    {
        priceTypeQualifierID => 'J',
        rAuthor              => 'C',
        rTitle               => 'B',
        rIsbn13              => 'A',
        rInstitution         => 'J',
        countryCode          => 'K',
        rUnits               => 'F',
        rListPrice           => 'D',
        rListPriceCurrency   => 'E',
        rDiscount            => 'G',
        rRevenue             => 'I',
        currencyCode         => 'E',
    };
}

sub _headerIdentifier { rIsbn13 => 'ISBN' }

sub _useIsSaleRec      { 1 }
sub _dateNormalization { 'month' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rTitle             { Common::UTF8::Encode( shift->_getByFieldName('rTitle')       || '' ) }
sub rInstitution       { Common::UTF8::Encode( shift->_getByFieldName('rInstitution') || '' ) }

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

sub priceType    {
    my $self = shift;

    my $clientID = Common::RSApp::GetClientID;
    # MMUS, RLPG, Willey, BKPub
    return 'rrp' if $clientID =~ /^318|346|324|335$/;

    $self->fail("Price Type not set for this client");
}

sub priceTypeQualifierID {
    my $self = shift;

    return unless $self->_getByFieldName('priceTypeQualifierID') || '';
    return BookPub::DB::Item::PriceTypeQualifier::kCorporate;
}

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;

    if ( $self->filename =~ /(\w{3})\w*_(\d{4})_/ ) {
        return sprintf( "%04d-%02d-%02d", $2, $months{ lc $1 }, 1 ) if exists $months{ lc $1 };
    }

    $self->fail("Unable to determine beginDate from file name.");
}

sub rUnits {
    my $self = shift;

    my $units   = $self->_getByFieldName('rUnits')   || 0;
    my $revenue = $self->_getByFieldName('rRevenue') || 0;

    return $revenue >= 0 ? abs $units : -1 * abs $units;
}

sub _isSaleRec {
    my $self = shift;

    return $self->rTitle && $self->rIsbn13;
}


1;