package BookPub::Import::Importer::Kobo::Version28;

use strict;

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

sub _headerIdentifier { ( dateBegin => 'Date' ) }

# 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 = {
        'us taxable' => {
            countryCode        => 'B',
            rState             => 'C',
            rPostalCode        => 'D',
            dateBegin          => 'A',
            isbn               => 'H',
            rTitle             => 'J',
            rAuthor            => 'I',
            rUnits             => 'G',
            rListPrice         => 'M',
            rListPriceCurrency => 'P',
            rPurchasePrice     => 'L',
            rCOGS              => 'N',
            rRevenue           => 'O',
        },
        'us non-taxable' => {
            countryCode        => 'B',
            rState             => 'C',
            rPostalCode        => 'D',
            dateBegin          => 'A',
            isbn               => 'H',
            rTitle             => 'J',
            rAuthor            => 'I',
            rUnits             => 'G',
            rListPrice         => 'M',
            rListPriceCurrency => 'P',
            rPurchasePrice     => 'L',
            rCOGS              => 'N',
            rRevenue           => 'O',
        },
        'world' => {
            currencyCode       => 'Q',
            countryCode        => 'B',
            rState             => 'C',
            rPostalCode        => 'D',
            dateBegin          => 'A',
            isbn               => 'F',
            rTitle             => 'H',
            rAuthor            => 'G',
            rUnits             => 'E',
            rListPrice         => 'K',
            rListPriceCurrency => 'N',
            rPurchasePrice     => 'J',
            rCOGS              => 'L',
            rRevenue           => 'P',
            conversionRate     => 'O',
        },
        '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 purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

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

sub rListPrice {
    my $self = shift;

    my $sheet             = lc( $self->sheetname );
    my $listPrice         = $self->_getByFieldName('rListPrice');
    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency');
    my $currencyCode      = $self->_getByFieldName('currencyCode');

    # We want to convert all list prices to the same currency as the revenue for Macmillan
    if ( ( $sheet =~ /^world/i || $sheet =~ /^returns/i ) && $currencyCode ne $listPriceCurrency && Common::RSApp::GetClientID == 318 ) {
        if ( $sheet =~ /^returns/i ) {

            # There's not actually a place for a converion rate on this sheet,
            # so let's just throw an error if we end up here.
            die "Conversion Rate missing";
        }
        my $conversionRate = $self->_getByFieldName('conversionRate');
        $listPrice *= $conversionRate;
    }

    return $listPrice;
}

sub rListPriceCurrency {
    my $self = shift;

    my $listPriceCurrency = $self->_getByFieldName('rListPriceCurrency');

    # We're converting the list prices for Macmillan, so we need to set this to the revenue's currency code.
    if ( Common::RSApp::GetClientID == 318 ) {
        $listPriceCurrency = $self->currencyCode;
    }

    return $listPriceCurrency;
}

sub currencyCode {
    my $self = shift;

    my $sheet = lc( $self->sheetname );
    my $currencyCode;
    if ( $sheet =~ /^us /i ) {
        $currencyCode = 'USD';
    } else {
        $currencyCode = $self->_getByFieldName('currencyCode');
    }

    return $currencyCode;
}

sub rState {
    my $self = shift;

    my $state = $self->_getByFieldName('rState');

    if ( $state eq '#N/A' ) {
        $state = '';
    }

    return $state;
}

sub priceType {
    my $self = shift;

    if ( $self->filename =~ /macmillan/i ) {
        my $countryCode = $self->countryCode();
        if ( $countryCode eq 'US' || $countryCode eq 'CA' ) {
            return 'agency';
        } else {
            return 'rrp';
        }
    } else {
        die "Unable to find Macmillan in file name.  Importer may need to be updated.";
    }
}

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

sub _isValidSaleRecord {
    my $self = shift;
    return ( $self->rTitle || $self->rIsbn10 || $self->rIsbn13 ) && $self->dateBegin;
}

1;
