package BookPub::Import::Importer::Kobo::Version5;

use strict;

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

sub _headerIdentifier { ( isbn => 'ISBN' ) }

# We have to do some odd things with the field map here because this importer has
# different column definitions of seperate tabs.  The map is defined by tab name below.
# The summary tab is ignored (returns and empty field set).
sub _fieldMap {
    my $self = shift;

    my $map = {
        'sales reporting' => {
            currencyCode => 'J',
            countryCode  => 'B',
            dateBegin    => 'A',
            isbn         => 'D',
            rTitle       => 'F',
            rAuthor      => 'E',
            rUnits       => 'C',
            rListPrice   => 'G',
            rCOGS        => 'H',
            rRevenue     => 'I',
        },
        'refunds' => {
            countryCode        => 'C',
            dateBegin          => 'A',
            isbn               => 'F',
            rTitle             => 'H',
            rAuthor            => 'G',
            rListPrice         => 'I',
            rListPriceCurrency => 'N',
            rCOGS              => 'J',
            rRevenue           => 'M',
        },
    };

    my $sheet = lc( $self->sheetname ) || return {};
    return {} if ( $sheet =~ /(invoice|credit note)/ );

    die "Unrecognized tab name '" . $self->sheetname . "'" unless ( $map->{$sheet} );

    return $map->{$sheet};
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub currencyCode {
    my $self = shift;

    return $self->_getOffset('currencyCode') ? $self->SUPER::currencyCode() : 'GBP';
}

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

    # The refund tab doesn't list units.
    if ( lc( $self->sheetname ) eq 'refunds' && !defined($units) ) {
        $units = -1;
    }

    return $units;
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');
    if ( $self->units < 0 && $revenue > 0 ) {
        return $revenue * -1;
    } else {
        return $revenue;
    }
}

1;
