package BookPub::Import::Importer::Vearsa;

use strict;

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

sub _fieldMap {
    {
        # Detail
        dateBegin          => 'O',
        rFormat            => 'AD',
        rPriceType         => 'AK',
        rAuthor            => 'Y',
        rTitle             => 'X',
        rIsbn13            => 'U',
        rImprint           => 'AC',
        countryCode        => 'AL',
        rClientProductID   => 'W',
        rReturns           => 'AG',
        rSales             => 'AF',
        rUnits             => 'AH',
        rUnitPrice         => 'AM',
        rListPrice         => 'BQ',
        rListPriceCurrency => 'AO',
        rRevenue           => 'BC',
        currencyCode       => 'I',
        rChannel           => 'N',
    };
}

sub _useIsSaleRec { 1 }

sub _dateFormat  { ['iso'] }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _headerIdentifier { ( rTitle => 'Product title' ) }

sub rFormat {
    my $self   = shift;
    my $format = $self->_getByFieldName('rFormat');

    if ( lc($format) eq 'ec101' ) {
        return BookPub::DB::Item::Sale::kFormatTypeEPub;
    }

    return $format;
}

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

    if ( !$price ) {
        return $unitPrice;
    }

    return $price;
}

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;

    # format the date
    if ( $date =~ /(\d{4})(\d{2})(\d{2})/ ) {
        $date = $1 . "-" . $2 . "-" . $3;
    }

    return $date;
}

sub priceType {
    my $self = shift;
    my $type = lc( $self->rPriceType ) || return;

    if ( int($type) == 1 || lc($type) eq 'agency' ) {
        $type = 'agency';
    } elsif ( int($type) == 2 || lc($type) eq 'wholesale' ) {
        $type = 'rrp';
    }

    return $type;
}

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

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

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

    return $sales >= 0 ? $sales : 0;
}

###
1;    # Play nicely.
###
