package BookPub::Import::Importer::Mackin::Version2;

use strict;

use lib '/app/tools/common/lib';
use Common::Assert;
use Data::Dumper;

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

sub _headerIdentifier { ( rIsbn13 => 'eISBN' ) }

sub _fieldMap {
    {
        rIsbn13       => 'B',
        rTitle        => 'C',
        rSubtitle     => 'D',
        rAuthor       => 'E',
        rUnits        => 'I',
        rUnitPrice    => 'K',
        rListPrice    => 'J',
        rDiscount     => 'L',
        rRevenue      => 'M',
        countryCode   => 'G',
        dateBegin     => 'A',
        rInstitution  => 'F',
        rPurchaseType => 'H',
    };
}

sub rServiceName         { 'Mackin Books' }
sub priceType            { 'rrp' }
sub productType          { shift->rProductType }
sub currencyCode         { 'USD' }
sub rListPriceCurrency   { 'USD' }

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

    # 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 purchaseType {
    my $self = shift;

    my $type = $self->_getByFieldName('rPurchaseType');
    return BookPub::DB::Item::Sale::kPurchaseTypeLoan if ($type =~ /^(?:C|M|S)$/);

    $self->fail("Unable to determine rPurchaseType from 'type'");
}

sub rProductType  {
    my $self = shift;

    my $fileName = $self->filename;
    if ( $fileName =~ /[ _]DIGITAL[ _]AUDIO/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook;
    }
    if ( $fileName =~ /[ _]EBOOKS/i ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Unable to determine rProductType.");
}

sub priceTypeQualifierID {
    my $self = shift;

    if ( $self->rProductType eq BookPub::DB::Item::Sale::kProductTypeAudioBook ) {
         return BookPub::DB::Item::PriceTypeQualifier::kCorporate
    }
    if ( $self->rProductType eq BookPub::DB::Item::Sale::kProductTypeEBook ) {
        my $format = uc($self->_getByFieldName('rPurchaseType')) || "";
        return BookPub::DB::Item::PriceTypeQualifier::kSchoolLibrary if $format eq 'S';
        return BookPub::DB::Item::PriceTypeQualifier::kCorporate if $format eq 'C';
    }

    $self->fail("Unable to determine priceTypeQualifierID.");
}

sub isFree {
    my $self = shift;

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

    return 'Y' if ($revenue == 0 && $units != 0);
    return 'N';
}

sub _useIsSaleRec { 1 }

sub _isSaleRec {
    my $self = shift;
    return $self->rTitle && $self->dateBegin;
}

###
1;    #
###
