package BookPub::Import::Importer::BISG::Version1;

use strict;

use Common::Country;

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

sub _fieldMap {
    {
        # Header
        rPriceType    => 'E',
        rPurchaseType => 'J',
        currencyCode  => 'F',
        countryCode   => 'K',

        # Detail
        serviceProductID => 'F',
        dateBegin        => 'E',
        isbn             => 'K',

        rTitle             => 'N',
        rAuthor            => 'O',
        rUnits             => 'U',
        rSales             => 'S',
        rReturns           => 'T',
        rListPrice         => 'Z',
        rListPriceCurrency => 'AB',
        rDiscount          => 'AC',
        rRevenue           => 'AP',
    };
}

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

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

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

    if ( $self->{_firstHeaderFound} ) {
        $self->{_currencyCode} = $self->_getByFieldName('currencyCode');
        $self->{_countryCode}  = $self->_getByFieldName('countryCode');
        $self->{_priceType}    = $self->_getByFieldName('rPriceType');
        $self->{_purchaseType} = $self->_getByFieldName('rPurchaseType');

        $self->{_firstHeaderFound} = undef;

    } elsif ( $countryCode && $countryCode eq 'Sales territory' ) {
        $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} );
        $self->fail("No country code found in the header")  unless ( $self->{_countryCode} );
        $self->fail("No price type found in the header")    unless ( $self->{_priceType} );
        $self->fail("No purchase type found in the header") unless ( $self->{_purchaseType} );
    }
}

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

    my $typeID =
        $type == 1  ? 'rrp'
      : $type == 41 ? 'agency'
      :               undef;

    $self->fail("Unknown price type '$type'") unless ($typeID);

    return $typeID;
}

sub currencyCode { shift->{_currencyCode} }
sub countryCode  { shift->{_countryCode} }

sub rPurchaseType { shift->{_purchaseType} }
sub rPriceType    { shift->{_priceType} }

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

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;
