package BookPub::Import::Importer::LearnOutLoud::Version2;

use strict;

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

use Date::Calc qw( Add_Delta_YMD  Add_Delta_YM );

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

sub _headerIdentifier { ( dateBegin => 'Date' ) }

sub _fieldMap {
    {
        dateBegin   => 'A',
        countryCode => 'H',
        isbn        => 'G',
        rTitle      => 'B',
        rAuthor     => 'C',
        rListPrice  => 'D',
        rDiscount   => 'E',
        rRevenue    => 'F',
    };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub currencyCode { 'USD' }

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

    if ( $date eq '' || !defined($date) ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isValidSaleRecord {
    my $self = shift;

    # If we've set the end of data flag in _processLine, we are done.
    if ( $self->{_endOfData} ) { return 0 }

    my $title = $self->_getByFieldName('rTitle');
    my $isbn  = $self->_getByFieldName('isbn');

    if ( ( !defined($title) || length($title) == 0 ) && ( !defined($isbn) || length($isbn) == 0 ) ) {
        $self->fail("Sale is missing both title and ISBN");
    }

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

sub countryCode {
    my $self = shift;
    my $code = $self->SUPER::countryCode();

    my $countryObj = Common::Country->Get($code) || $self->fail("Unknown country code '$code'");

    return $countryObj->alpha2();
}

sub units { '1' }

1;
