package BookPub::Import::Importer::BlackstoneAudio::Version6;

use strict;
use warnings;

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

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


sub _headerIdentifier { rTitle => 'Book Title' }

sub _fieldMap {
    {
        rProductType     => 'D',
        rTitle           => 'A',
        rIsbn13          => 'J',
        rClientProductID => 'C',
        serviceProductID => 'B',
        rUnits           => 'F',
        rListPrice       => 'E',
        rCOGS            => 'H',
        rRevenue         => 'I',
    }
}

sub _unverifiedFieldMap {
    {
        _salesDate => 'A2',
    }
}

sub _useIsSaleRec      { 1 }
sub rServiceName       { 'Blackstone Audio' }
sub priceType          { 'rrp' }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { shift->rProductType }


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 dateBegin { ($_[0]->_getPeriodDates())[0] }
sub dateEnd   { ($_[0]->_getPeriodDates())[1] }

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

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

    my $dateStr = $self->_getByFieldName('_salesDate') || '';
    if ( $dateStr =~ /(\w{3,9}) (\d{4})(?: Sales)?$/i ) {
        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: '$dateStr'");
}

sub rProductType {
    my $self = shift;

    my $type = $self->_getByFieldName('rProductType') || '';
    if ( $type =~ /^(?:MP3|Retail|Library) CD$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook;
    }

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

sub rIsbn13 {
    my $self = shift;

    my $isbn = $self->_getByFieldName('rIsbn13') || '';
    $isbn =~ s/-//g;

    return $isbn;
}

sub isFree {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

    return if !$self->rIsbn13 && !$self->rTitle;

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


1;
