package BookPub::Import::Importer::Kobo::Version25;

use strict;

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

sub _headerIdentifier { ( rUnits => 'Quantity' ) }

# 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 = {
        'canada' => {
            currencyCode       => 'P',
            countryCode        => 'B',
            rState             => 'C',
            rPostalCode        => 'D',
            dateBegin          => 'A',
            isbn               => 'F',
            rTitle             => 'H',
            rAuthor            => 'G',
            rUnits             => 'E',
            rListPrice         => 'J',
            rListPriceCurrency => 'M',
            rCOGS              => 'K',
            rRevenue           => 'O',
        },
        'cad refunds' => {
            currencyCode       => 'L',
            countryCode        => 'B',
            rState             => 'C',
            rPostalCode        => 'D',
            dateBegin          => 'A',
            isbn               => 'F',
            rTitle             => 'H',
            rAuthor            => 'G',
            rUnits             => 'E',
            rListPrice         => 'I',
            rListPriceCurrency => 'L',
            rCOGS              => 'J',
            rRevenue           => 'K',
        },

    };

    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    { 'agency' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _dateFormat { [ 'us', 'iso' ] }

sub units {
    my $self = shift;

    my $units = $self->SUPER::units();

    if ( lc( $self->sheetname ) =~ /(refund|gifts)/i ) {
        return $units ? $units * -1 : -1;
    } else {
        return $units ? $units : 1;
    }
}

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;
}

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $title;
}

sub rSubtitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $subtitle;
}

1;
