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

use strict;

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        4 => {
            currencyCode => 'M',
            dateBegin    => 'F',
            rIsbn13      => 'C',
            rTitle       => 'D',
            rAuthor      => 'E',
            rUnits       => 'J',
            rListPrice   => 'G',
            rDiscount    => 'I',
            rRevenue     => 'L',
        },
    );

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

sub _headerIdentifier { ( dateBegin => 'PurchaseDate' ) }

sub rServiceName { "OCLC" }

sub _useIsSaleRec { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub countryCode                { shift->{_countryCode} }
sub priceType                  { 'rrp' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
        return $date;
    }

    return $date

}

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    # Let's grab the country code from the filename.
    if ( !$self->{_countryCode} ) {
        my $filename = $self->filename;
        if ( $filename =~ m/\d{8}_(\w{2})/i ) {
            $self->{_countryCode} = "$1";
        }
    }

    # Still didn't find it?  Give up.
    if ( !$self->{_countryCode} ) {
        $self->errstr('Unable to find country code in file name');
        return undef;
    }

}

sub _isSaleRec {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $isbn      = $self->_getByFieldName('rIsbn13');
    my $title     = $self->_getByFieldName('rTitle');
    my $author    = $self->_getByFieldName('rAuthor');

    # We're going to skip the subtotal lines, which are blank for these fields
    if ( !$dateBegin && !$isbn && !$title && !$author ) {
        return 0;
    }

    return $self->SUPER::_isSaleRec();
}

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