package BookPub::Import::Importer::HooplaDigital::v3;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Date::Calc qw(Days_in_Month);

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


sub _fieldMap {
    {
        rServiceName => 'A2',
        dateBegin    => 'A3',
        rProductType => 'B5',
        rTitle       => 'A',
        rIsbn13      => 'B',
        rUnits       => 'F',
        rListPrice   => 'E',
        rRevenue     => 'H',
    };
}

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 _headerIdentifier  { rIsbn13 => 'ISBN' }
sub _useIsSaleRec      { 1 }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeLoan }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub rServiceName       { 'Hoopla Digital' }
sub productType        { shift->rProductType }

sub _getPeriodDates {
    my ($self, $type) = @_;

    if ( $self->{__date_begin} && $self->{__date_end} ) {
        return $self->{__date_begin}, $self->{__date_end};
    }

    # Monthly Circulation Report | July 2020
    my $date = $self->_getByFieldName('dateBegin') || '';
    if ( $date =~ /\| ([a-zA-Z]{3,9}) (\d{4})$/ ) {
        my $month = $months{ substr( lc $1, 0, 3 ) };
        my $year  = $2;
        $self->{__date_begin} = sprintf "%04d-%02d-%02d", $year, $month, 1;
        $self->{__date_end}   = sprintf "%04d-%02d-%02d", $year, $month, Days_in_Month( $year, $month );
        return $self->{__date_begin}, $self->{__date_end};
    }

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

sub dateBegin { ($_[0]->_getPeriodDates())[0] }
sub dateEnd   { ($_[0]->_getPeriodDates())[1] }

sub rProductType {
    my $self = shift;

    my $rProductType = $self->_getByFieldName('rProductType') || '';
    if ( $rProductType =~ /^Macmillan Entangled eBooks$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Couldn't determine product_type from: '$rProductType'");
}

sub priceType {
    my $self = shift;

    if ( Common::RSApp::GetClientID == 318 ) {    # MMUS
        return 'agency';
    }

    return 'rrp';
}

sub _isSaleRec {
    my $self = shift;

    return if $self->{_endOfData};

    unless ( $self->SUPER::_isSaleRec ) {
        $self->{_endOfData} = 1;
        return;
    }

    return 1;
}


1;
