package BookPub::Import::Importer::SainsburysEntertainment::Version4;

use strict;

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

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

sub _fieldMap {
    {
        currencyCode           => 'K',
        dateBegin              => 'H',
        isbn                   => 'A',
        rTitle                 => 'B',
        rSubtitle              => 'C',
        rAuthor                => 'D',
        rImprint               => 'F',
        rSales                 => 'I',
        rReturns               => 'J',
        rListPrice             => 'M',
        rListPriceCurrency     => 'K',
        rPurchasePrice         => 'N',
        rPurchasePriceCurrency => 'K',
        rTaxAmount             => 'O',
        rRevenue               => 'Q',

    };
}

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

sub countryCode   { 'GB' }
sub priceType     { 'rrp' }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub _dateFormat   { ['iso'] }
sub _useIsSaleRec { 1 }

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

    if ( $isbn =~ /total/ ) {
        $self->{_endOfData} = 1;
    }

    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 $self->SUPER::_isSaleRec();
}

sub rAuthor {
    my $self   = shift;
    my $author = $self->_getByFieldName('rAuthor');

    # We just want the first name if there is a list.
    if ( $author =~ /^(.*?);/ ) {
        $author = $1;
    }

    return $author;
}

sub rDiscount {
    my $self = shift;
    my $discount;
    my $revenue = $self->_getByFieldName('rRevenue');
    my $list    = $self->_getByFieldName('rListPrice');

    if ( defined $list && $list != 0 ) {
        $discount = 1 - ( $revenue / $list );
    }

    return $discount;
}

sub _getDateBegin {
    my $date = shift->SUPER::_getDateBegin() || return;
    my $d = substr( $date, 0, 10 );

    return $d;
}

1;
