package BookPub::Import::Importer::EBook::Version7;

use strict;

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

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

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _fieldMap {
    {
        rPriceType         => 'V',
        serviceProductID   => 'M',
        currencyCode       => 'V',
        conversionRate     => 'W',
        countryCode        => 'O',
        rState             => 'P',
        rPostalCode        => 'T',
        dateBegin          => 'L',
        rFormat            => 'I',
        rIsbn13            => 'H',
        rTitle             => 'D',
        rAuthor            => 'E',
        rImprint           => 'C',
        rComments          => 'AF',
        rListPrice         => 'U',
        rListPriceCurrency => 'V',
        rDiscount          => 'AD',
        rUnitPrice         => 'X',
    };
}

sub _unverifiedFieldMap {
    { eIsbn13 => 'G', };
}

sub rRevenue {
    my $self      = shift;
    my $listPrice = $self->_getByFieldName('rListPrice');
    my $discount  = $self->_getByFieldName('rDiscount');
    my $revenue   = $listPrice * ( 1 - ( $discount / 100 ) );
    return $revenue;
}

sub rListPrice {
    my $self      = shift;
    my $listPrice = $self->_getByFieldName('rListPrice');
    return abs($listPrice);
}

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

    return $price eq 0 ? 'Y' : 'N';
}

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

    my $eisbn = $self->_getByFieldName('eIsbn13');

    if ( defined($isbn) && $isbn ne '' ) {
        return $isbn;
    } else {
        return $eisbn;
    }
}

sub _isValidSaleRecord {
    my $self    = shift;
    my $eIsbn13 = $self->_getByFieldName('eIsbn13');

    return $self->rTitle && ( $self->rIsbn10 || $self->rIsbn13 || $eIsbn13 ) && $self->dateBegin;
}

sub units {
    my $revenue = shift->rRevenue || return 1;
    return $revenue < 0 ? -1 : 1;
}

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

    $currency =~ /^(\w{3})/i;

    return $1;
}

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

    $type =~ /\((.*)\)/;

    # If a price type is supplied in the currency field and it is agency then
    # set the price type.
    if ( $1 && $1 =~ /agency/i ) {
        return 'agency';

        # If no price type is set then us rrp
    } elsif ( $type !~ /\(/ ) {
        return 'rrp';

        # Just incase we get something different in the price type.
    } else {
        $self->fail("Unable to determine price type from '$type'");
    }
}

1;
