package BookPub::Import::Importer::InAudio::Version8;

use strict;
use warnings;

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

sub _headerIdentifier { rIsbn13 => 'ISBN #' }

sub _fieldMap {
    {
        dateBegin            => 'B2',
        dateEnd              => 'B2',
        rPurchaseType        => 'B',
        purchaseType         => 'B',
        priceType            => 'L',
        priceTypeQualifierID => 'B',
        rTitle               => 'A',
        rIsbn13              => 'E',
        countryCode          => 'I',
        serviceProductID     => 'D',
        rUnits               => 'M',
        rListPrice           => 'K',
        rListPriceCurrency   => 'J',
        rDiscount            => 'C',
        rRevenue             => 'S',
        currencyCode         => 'R',
        rFee                 => 'P',
        rPromoCode           => 'H',
        rChannel             => 'G',
    };
}

sub _useIsSaleRec  { 1 }
sub productType    { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub rProductType   { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub _getDateBegin  { shift->{_dateBegin} }
sub _getDateEnd    { shift->{_dateEnd} }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName( service_id => shift->serviceID );
}

sub purchaseType    {
    my $self = shift;

    my $type = $self->_getByFieldName('rPurchaseType') || '';

    if ( $type =~ /^(?:Retail|Library(?:-Limited Circ)?)$/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload ;
    } elsif ( $type =~ /^(?:Subscription-Unlimited|Subscription-Credit Based|Subscription-Supplemental Credit|Pool|Subscription-Combined Portions)$/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL;
    } elsif ( $type =~ /^(?:Prepaid|Unlimited) Subscription$/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL;
    } elsif ( $type =~ /^(?:Library-Pay Per Use|Library Per Circ)$/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }

    $self->fail( "Could not determine purchase type from $type" );
}

sub priceType    {
    my $self = shift;

    my $type = $self->_getByFieldName('priceType') || '';
    return 'rrp' if $type =~ /^(?:Gross|Net)$/i;

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

sub priceTypeQualifierID {
    my $self = shift;

    my $type = $self->_getByFieldName('priceTypeQualifierID') || '';
    return $type =~ /^Library/i ? BookPub::DB::Item::PriceTypeQualifier::kCorporate : undef;
}

sub rDiscount {
    my $self = shift;

    my $discount = $self->_getByFieldName('rDiscount') || 0;
    $discount =~ s/%//g;

    return $discount;
}

sub countryCode {
    my $self = shift;

    my $countryCode = $self->_getByFieldName('countryCode') || '';

    if ( Common::RSApp::GetClientID() =~ /^346$/ ) { # RLPG
        return $countryCode || 'US';
    }

    return $countryCode if $countryCode;

    $self->fail("Unable to determine country code from: '$countryCode'");
}

sub rUnitPrice {
    my $self = shift;

    if ( $self->rUnits ) {
        return $self->rRevenue / $self->rUnits;
    }

    return 0;
}

sub isFree {
    my $self = shift;

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

sub rListPriceCurrency {
    my $self = shift;
    return $self->_getByFieldName('rListPriceCurrency') || '';
}

sub rPromoCode {
    my $self = shift;
    return $self->_getByFieldName('rPromoCode') || '';
}

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 _preProcess {
    my ($self, %args) = @_;

    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        next unless $args{sheet_names}->[$sheetnum] =~ /^Summary$/i;

        # Cell B2 on the Summary tab
        if ( $sheet->[1][1] =~ /(\w{3,9}) (\d{1,2}),? (\d{4}) - (\w{3,9}) (\d{1,2}),? (\d{4})/ ) {
            $self->{_dateBegin} = sprintf "%04d-%02d-%02d", $3, $months{ substr(lc $1, 0, 3) }, $2;
            $self->{_dateEnd}   = sprintf "%04d-%02d-%02d", $6, $months{ substr(lc $4, 0, 3) }, $5;
            return 1;
        }
    }

    return 1;
}

sub _isSaleRec {
    my $self = shift;

    # skip blank lines
    if ( !$self->rTitle && !$self->rIsbn13 && !$self->rUnits && !$self->rRevenue ) {
        return 0;
    }

    if ( !$self->rUnits && $self->rRevenue > 0 ) {
        $self->fail("No units but positive revenue.");
    } elsif ( !$self->rUnits && $self->rRevenue < 0 ) {
        $self->fail("No units but negative revenue.");
    } elsif ( !$self->rUnits && !$self->rRevenue ) {
        $self->fail("No units and no revenue.");
    }


    return 1;
}


1;
