package BookPub::Import::Importer::BISG::Version2;

use strict;

use lib '/app/tools/common/lib';
use Common::Country;

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

sub _fieldMap {
    {
        # Header
        currencyCode => 'F',

        # Detail
        rPriceType         => 'M',
        countryCode        => 'N',
        rState             => 'O',
        rPostalCode        => 'P',
        dateBegin          => 'B',
        rFormat            => 'H',
        isbn               => 'D',
        rTitle             => 'E',
        rAuthor            => 'F',
        rImprint           => 'G',
        rUnits             => 'L',
        rSales             => 'J',
        rReturns           => 'K',
        rListPrice         => 'Q',
        rListPriceCurrency => 'S',
        rDiscount          => 'T',
        rRevenue           => 'X',

    };
}

my %formatTypes = ( 'e107' => BookPub::DB::Item::Sale::kFormatTypePDF, );

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

sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub currencyCode { shift->{_currencyCode} }

sub _processHeader {
    my $self         = shift;
    my $currencyCode = $self->_getByFieldName('currencyCode');

    if ( $self->{_firstHeaderFound} ) {
        $self->{_currencyCode} = $self->_getByFieldName('currencyCode');

        $self->{_firstHeaderFound} = undef;

    } elsif ( $currencyCode && $currencyCode eq 'Reporting currency' ) {
        $self->{_firstHeaderFound} = 1;
    }

    # Check to ensure we found the first header
    if ( $self->_isHeader() ) {
        $self->fail("No currency code found in the header") unless ( $self->{_currencyCode} );
    }
}

sub _isValidSaleRecord {
    my $self = shift;
    if ( $self->_getByFieldName('dateBegin') eq 'Total number of line items' ) {
        return undef;
    }

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

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

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

sub _getDateBegin {
    my $date = shift->SUPER::_getDateBegin() || return;
    my $d = substr( $date, 0, 4 ) . "-" . substr( $date, 4, 2 ) . "-" . substr( $date, 6 );

    return $d;
}

sub formatType {
    my $self = shift;
    my $rFormat = $self->rFormat || return;

    my $formatType = $formatTypes{ lc($rFormat) };

    $self->fail("Unknown format type '$rFormat'") unless $formatType;

    return $formatType;
}

1;
