package BookPub::Import::Importer::KiwiTech::Version1;

use strict;

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

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

sub _fieldMap {
    {
        currencyCode       => 'J',
        countryCode        => 'E',
        dateBegin          => 'A',
        dateEnd            => 'B',
        rIsbn13            => 'C',
        rTitle             => 'D',
        rAuthor            => 'D',
        rUnits             => 'I',
        rSales             => 'H',
        rReturns           => 'H',
        rListPrice         => 'F',
        rListPriceCurrency => 'G',
        rRevenue           => 'O',
        rUnitPrice         => 'N',
    };
}

sub priceType    { 'agency' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub formatType   { BookPub::DB::Item::Sale::kFormatTypeAppleMultimedia }

# units are reported in column I and an S or R in column H
# tells us if it's a Sale or Return, hence we need to overload
# units here.

sub units {
    my $self         = shift;
    my $units        = $self->rUnits();
    my $saleOrReturn = $self->_getByFieldName('rSales');

    # S for Sale, R for Return
    return lc($saleOrReturn) eq 's' ? $units : 0 - $units;
}

sub rSales {
    my $self  = shift;
    my $sales = $self->_getByFieldName('rSales');

    return lc($sales) eq "s" ? $self->rUnits() : 0;
}

sub rReturns {
    my $self    = shift;
    my $returns = $self->_getByFieldName('rReturns');

    return lc($returns) eq "r" ? $self->rUnits : 0;
}

# Title and Author are both in rTitle field as 'XXX by YYY', so
# we're splitting that up.
sub rTitle {
    my $self = shift;
    my $string = $self->_getByFieldName('rTitle') || return;

    # everything before the last " by "
    my ($title) = $string =~ /(.*) by .*/;

    return $title;
}

sub rAuthor {
    my $self = shift;
    my $string = $self->_getByFieldName('rTitle') || return;

    # everything after the last " by "
    my ($author) = $string =~ /.* by (.*)/;

    return $author;
}

sub rIsbn13 {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13') || return;

    # strip off the ISBN label
    $isbn =~ s/^ISBN: //;

    return length($isbn) == 13 ? $isbn : undef;
}

1;
