package BookPub::Import::Importer::Oyster;

use strict;
use Date::Calc qw(Days_in_Month Decode_Month);

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

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            rPriceType         => 'P',
            countryCode        => 'N',
            dateBegin          => 'D',
            dateEnd            => 'E',
            rIsbn13            => 'H',
            rTitle             => 'I',
            rAuthor            => 'J',
            rSales             => 'W',
            rReturns           => 'X',
            rListPrice         => 'O',
            rListPriceCurrency => 'Q',
            rRevenue           => 'AC',
        },
        4 => {
            rPriceType         => 'P',
            currencyCode       => 'F',
            countryCode        => 'N',
            dateBegin          => 'D',
            dateEnd            => 'E',
            rIsbn13            => 'H',
            rTitle             => 'I',
            rAuthor            => 'J',
            rUnits             => 'M',
            rSales             => 'K',
            rReturns           => 'L',
            rListPrice         => 'O',
            rListPriceCurrency => 'R',
            rDiscount          => 'Q',
            rRevenue           => 'AD',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            subtotal => 'AB',
        },
        4 => {
            subtotal => 'AC',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _headerIdentifier { ( rIsbn13 => 'Main product ID#' ) }

sub currencyCode {
    my $self = shift;

    if ( defined $self->_getByFieldName('currencyCode') ) {
        return $self->_getByFieldName('currencyCode');
    } else {
        return 'USD';
    }
}

sub priceType {
    my $self = shift;
    my $type = $self->rPriceType || return;

    my $typeID =
        $type == 1  ? 'rrp'
      : $type == 41 ? 'agency'
      :               undef;

    $self->fail("Unknown price type '$type'") unless ($typeID);

    return $typeID;
}

sub _isSaleRec {
    my $self = shift;

    my $subtotal = $self->_getByFieldName('subtotal');
    if ( lc($subtotal) eq 'total due' ) {
        return;
    }

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

###
1;    # Play nicely.
###
