package BookPub::Import::Importer::OCLC::Version5;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Country;

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

sub _fieldMap {
    {
        dateBegin          => 'A',
        dateEnd            => 'A',
        rAuthor            => 'I',
        rTitle             => 'H',
        rIsbn13            => 'G',
        rState             => 'D',
        countryCode        => 'E',
        rUnits             => 'M',
        rListPrice         => 'L',
        rListPriceCurrency => 'O',
        rRevenue           => 'N',
        currencyCode       => 'O',
    };
}

sub _headerIdentifier { rTitle => 'Title' }

sub _useIsSaleRec        { 1 }
sub rServiceName         { 'OCLC' }
sub priceType            { 'rrp' }
sub rProductType         { BookPub::DB::Item::Sale::kProductTypeEBook }
sub productType          { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType         { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceTypeQualifierID { BookPub::DB::Item::PriceTypeQualifier::kCorporate }


sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';
    # YYYY-MM-DD
    if ( $date =~ /^(\d{4})\D(\d{1,2})\D(\d{1,2})$/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, $3;
    }

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

sub dateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || '';
    # YYYY-MM-DD
    if ( $date =~ /^(\d{4})\D(\d{1,2})\D(\d{1,2})$/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, $3;
    }

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

sub rTitle {
    my $self = shift;

    my $rTitle = $self->_getByFieldName('rTitle') || '';
    return $rTitle if $rTitle;

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

sub rUnitPrice {
    my $self = shift;

    return $self->rRevenue / $self->rUnits;
}

sub countryCode {
    my $self = shift;

    my $code = $self->_getByFieldName('countryCode') || '';
    my $countryObj = Common::Country->Get($code);
    return $countryObj->alpha2() if $countryObj;

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

sub isFree {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

    my $rTitle  = $self->_getByFieldName('rTitle') || '';
    my $currencyCode = $self->_getByFieldName('currencyCode') || '';

    return 0 if !$rTitle && !$currencyCode;

    return 1;
}


1;