package BookPub::Import::Importer::Kobo::Version14;

use strict;

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

sub _ignoreSheetIndex { 0 }
sub _sheetIndex       { 'all' }

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

sub _requiredColumnMap {
    {
        countryCode        => [ 'Billing Country', 'Country' ],
        dateBegin          => 'Date',
        rPostalCode        => 'Postal Code',
        rTitle             => 'Title',
        isbn               => 'ISBN',
        rAuthor            => 'Author',
        rUnits             => [ 'QTY',             'Qty' ],
        rListPrice         => 'List Price',
        rListPriceCurrency => 'List Price Currency',
        rCOGS              => 'COGS %',
        rRevenue           => 'Net Due \(COGS\)',
        rState             => 'State',
    };
}

sub _optionalColumnMap {
    {
        rRevenue       => 'COGS in Contractual Currency',
        currencyCode   => 'Currency',
        conversionRate => 'Foreign Exchange rate to Contractual Currency',
    };
}

sub priceType    { 'agency' }
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 $date if ($date);

    return unless ( $self->filename =~ /(\w{3}).(\d{4})/ );
    my $fileDate = "$1-$2";

    $self->fail( "Failed to pull date from filename: " . $self->filename ) unless ($fileDate);
    return $fileDate;
}

sub _dateNormalization {
    my $self = shift;

    if ( $self->SUPER::_getDateBegin() ) {
        return;
    } else {
        return 'month';
    }
}

sub countryCode {
    return shift->SUPER::countryCode() || 'US';
}

sub currencyCode {
    return shift->SUPER::currencyCode() || 'USD';
}

sub units {
    my $self = shift;

    if ( lc( $self->sheetname ) =~ /(refund|gift)/i ) {
        return -1;
    }

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

    return $units ? $units : 1;
}

sub isFree {
    if ( lc( shift->sheetname ) eq 'promotions' ) {
        return 'Y';
    }

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

sub rState {
    my $state = shift->SUPER::rState;

    return !$state || $state eq 'NULL' ? undef : $state;
}

sub rPostalCode {
    my $postalCode = shift->SUPER::rPostalCode || return;
    $postalCode =~ s|/|-|;
    $postalCode =~ s/_//g;
    $postalCode =~ s/-$//g;

    if ( $postalCode =~ m/^\w{2} (\d{5})$/ ) {
        $postalCode = $1;
    }

    return $postalCode =~ /\d/ ? $postalCode : undef;
}

1;
