package BookPub::Import::Importer::Kobo::Version31;

use strict;

use lib '/app/tools/common/lib';
use Common::Postal;

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

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

# 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 = {
        'agency' => {
            currencyCode           => 'W',
            conversionRate         => 'U',
            countryCode            => 'C',
            rState                 => 'D',
            rPostalCode            => 'E',
            dateBegin              => 'A',
            isbn                   => 'K',
            rTitle                 => 'M',
            rAuthor                => 'L',
            rImprint               => 'J',
            rUnits                 => 'H',
            rSales                 => 'F',
            rReturns               => 'G',
            rListPrice             => 'Q',
            rListPriceCurrency     => 'T',
            rPurchasePrice         => 'P',
            rPurchasePriceCurrency => 'T',    # because we're using publisher price,
                                              # we'll use list price currency as we
                                              # do in the other versions
            rCOGS                  => 'R',
            rRevenue               => 'V',
        },
    };

    $map->{wholesale} = $map->{agency};       # wholesale tab maps just like agency tab

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

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

    return $map->{$sheet};
}

sub priceType {
    my $self = shift;

    my $map = {
        'agency'    => 'agency',
        'wholesale' => 'rrp',
    };

    my $sheet = lc( $self->sheetname );

    return $map->{$sheet};
}

sub postalCode {
    my $self = shift;

    my $postalCode;

    if ( my $rPostalCode = $self->rPostalCode() ) {
        if ( my $postal = Common::Postal->new( $self->countryCode() ) ) {
            $postalCode = $postal->formatPostalCode($rPostalCode);

            # Let's try it again with spaces removed.
            if ( !$postalCode ) {
                my $rPostalCodeClean = $rPostalCode;
                $rPostalCodeClean =~ s/ //g;
                $postalCode = $postal->formatPostalCode($rPostalCodeClean);
            }

            # Ok, let's just ignore it.

            if ( !$postalCode ) {
                return;
            }
        }
    }

    return $postalCode;
}

1;
