package BookPub::Import::Importer::Kobo::Version12;

use strict;

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

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

# 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 = {
        'partners' => {
            currencyCode => 'K',
            countryCode  => 'B',
            dateBegin    => 'A',
            isbn         => 'F',
            rTitle       => 'D',
            rAuthor      => 'E',
            rUnits       => 'C',
            rListPrice   => 'H',
            rCOGS        => 'I',
            rRevenue     => 'J',
        },
        'kobo' => {
            currencyCode => 'K',
            countryCode  => 'B',
            dateBegin    => 'A',
            isbn         => 'F',
            rTitle       => 'D',
            rAuthor      => 'E',
            rUnits       => 'C',
            rListPrice   => 'H',
            rCOGS        => 'I',
            rRevenue     => 'J',
        },
        'gifts' => {
            currencyCode => 'H',
            dateBegin    => 'A',
            isbn         => 'B',
            rTitle       => 'C',
            rAuthor      => 'D',
            rListPrice   => 'E',
            rCOGS        => 'F',
            rRevenue     => 'G',
        },
    };

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

    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 _dateFormat { [ 'iso', 'excel', 'text', 'eur' ] }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->SUPER::_getDateBegin() || return;
    if ( $date =~ s/\..*$//g ) {
        $date = $date - 2;
    }

    return $date;
}

sub countryCode {
    my $self    = shift;
    my $country = $self->SUPER::countryCode();

    return lc( $self->sheetname ) eq 'gifts' ? 'US' : $country;
}

sub units {
    my $self = shift;
    my $units = $self->rUnits || 1;
    $units *= -1 if ( lc( $self->sheetname ) eq 'gifts' );

    return $units;
}

sub rSales {
    if ( shift->rReturns ) {
        return 0;
    }

    return;
}

sub revenue {
    my $self    = shift;
    my $units   = $self->units();
    my $revenue = $self->SUPER::revenue();

    if ( $units && $units < 0 && $revenue && $revenue > 0 ) {
        return $revenue * -1;
    }

    return $revenue;
}
1;
