package BookPub::Import::Importer::Blinkbox;

use strict;

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

sub _headerIdentifier { ( rTitle => 'Product Title' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            currencyCode           => 'L',
            dateBegin              => 'A',
            rIsbn13                => 'D',
            rTitle                 => 'E',
            rAuthor                => 'F',
            rImprint               => 'C',
            rUnits                 => 'G',
            rListPrice             => 'I',
            rListPriceCurrency     => 'L',
            rPurchasePrice         => 'H',
            rPurchasePriceCurrency => 'L',
            rDiscount              => 'O',
            rRevenue               => 'P',

        },
    );

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

sub priceType     { 'agency' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub countryCode   { 'GB' }
sub _useIsSaleRec { 1 }

sub _processLine {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');

    if ( $date && $date =~ m/Grand Total/i ) {
        if ( $self->{_processReturns} && $self->{_processReturns} == 1 ) {
            $self->{_endOfData}      = 1;
            $self->{_processReturns} = 0;
            return;
        } else {
            $self->{_processReturns} = 1;
            $self->{_headerFound}    = 0;
            return;
        }
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

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

sub rTaxAmount {
    my $self = shift;

    my $purchasePrice = $self->_getByFieldName('rPurchasePrice');
    my $listPrice     = $self->_getByFieldName('rListPrice');
    my $units         = $self->_getByFieldName('rUnits');

    my $taxAmount = $units * ( $purchasePrice - $listPrice );
    if ( $self->{_processReturns} ) {
        $taxAmount = $taxAmount * -1;
    }

    return $taxAmount;
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

    if ( $self->{_processReturns} ) {
        $revenue = $revenue * -1;
    }

    return $revenue;
}

sub rUnits {
    my $self  = shift;
    my $units = $self->_getByFieldName('rUnits');

    if ( $self->{_processReturns} ) {
        $units = $units * -1;
    }

    return $units;
}

1;
