package BookPub::Import::Importer::RecordedBooks::Version1;

use strict;

use Spreadsheet::ParseExcel::Utility;

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

sub _headerIdentifier { ( rTitle => 'TITLE' ) }

sub _fieldMap {
    {
        currencyCode     => 'P',
        countryCode      => 'O',
        rState           => 'M',
        rPostalCode      => 'N',
        dateBegin        => 'L',
        rClientProductID => 'D',
        rIsbn13          => 'C',
        rTitle           => 'E',
        rAuthor          => 'F',
        rUnits           => 'G',
        rListPrice       => 'H',
        rDiscount        => 'J',
        rRevenue         => 'K',
    };
}

sub _unverifiedFieldMap {
    {
        headerProductType => 'A2',
        agency            => 'A',
    };
}

sub _useIsSaleRec { 1 }
sub priceType     { 'rrp' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _isSaleRec {
    my $self = shift;

    my $agency = $self->_getByFieldName('agency');

    if ( $agency =~ m/total/i ) {
        return 0;
    }

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

sub productType {
    my $self    = shift;
    my $typeStr = $self->_getByFieldName('headerProductType');

    if ( $typeStr =~ m/eaudio/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook;
    } elsif ( $typeStr =~ m/ebook/i ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    } else {
        $self->fail("Cannot find product type: $typeStr");
    }
}

sub discount {
    my $self     = shift;
    my $discount = $self->_getByFieldName('rDiscount');
    $discount = 1 - $discount;

    return $discount;
}

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

}

1;
