package BookPub::Import::Importer::Texidium;

use strict;

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

sub _headerIdentifier { ( rIsbn13 => 'ebook ISBN' ) }

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            dateBegin     => 'D2',
            dateEnd       => 'D4',
            rPurchaseType => 'R',
            rAuthor       => 'Q',
            rTitle        => 'M',
            rIsbn13       => 'L',
            rInstitution  => 'K1',
            rReturns      => 'T',
            rSales        => 'S',
            rUnits        => 'U',
            rUnitPrice    => 'O',
            rListPrice    => 'N',
            rRevenue      => 'X',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            totalLine => 'A',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub countryCode                { 'CA' }
sub currencyCode               { 'USD' }
sub _dateFormat                { [ 'us', 'iso' ] }

sub rUnitPrice {
    my $self  = shift;
    my $price = $self->_getByFieldName('rUnitPrice');

    $price =~ s/\$//g;
    return $price;
}

sub rListPrice {
    my $self  = shift;
    my $price = $self->_getByFieldName('rListPrice');

    $price =~ s/\$//g;
    return $price;
}

sub rDiscount {
    my $self = shift;
    my $discount;
    my $unitPrice = $self->rUnitPrice();
    my $listPrice = $self->rListPrice();

    if ($listPrice) {
        $discount = 1 - ( $unitPrice / $listPrice );
    }

    return $discount;
}

sub rReturns {
    my $self = shift;
    my $returns = $self->SUPER::rReturns() || return;

    return $returns < 0 ? abs($returns) : 0;
}

sub purchaseType {
    my $self = shift;
    my $type = $self->_getByFieldName('rPurchaseType');

    if ( $type =~ /perpetual/i ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    }
}

sub _processLine {
    my $self      = shift;
    my $totalLine = $self->_getByFieldName('totalLine');

    if ( $totalLine =~ /totals/i ) {
        $self->{_endOfData} = 1;
        return;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

    return if ( !$self->rPurchaseType()
        && !$self->rTitle()
        && !$self->rIsbn13() );

    return $self->SUPER::_isSaleRec();
}

1;
