package BookPub::Import::Importer::DNAML::Base;

use strict;

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

####
#    Process Control
####

sub _fieldmap { die "must be overloaded" }

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

# Need to grab the date and discount from the header rows
sub _processHeader {
    my $self = shift;

    $self->_storeDates();

    if ( $self->_isHeader() ) {
        $self->_storeDiscount();
        $self->_storeCurrency();
        $self->_validateHeaderData();
    }
}

sub _storeDiscount {
    my $self = shift;

    return if ( $self->{_discount} );

    my $discount = $self->_getByFieldName('rDiscount');

    if ( $discount && $discount =~ /Net Price \((\d+)%\)/ ) {
        $self->{_discount} = $1 / 100;
    }

    die "Could not determine discount rate from '$discount'"
      unless ( $self->rDiscount );
}

sub _storeCurrency {
    my $self = shift;

    return if ( $self->{_currency} );

    my $currency = $self->_getByFieldName('currencyCode');

    if ( $currency && $currency =~ /Owed to.*\((\w+)\)/i ) {
        $self->{_currency} = $1;
    }

    die "Could not determine currency code from '$currency'"
      unless ( $self->currencyCode );
}

sub _storeDates {
    my $self = shift;

    return if ( $self->{_dateBegin} );

    my $date = $self->_getByFieldName('dateBegin');

    if ( $date && $date =~ /(\d{1,2}\/\d{1,2}\/\d{4})\s?to\s?(\d{1,2}\/\d{1,2}\/\d{4})/i ) {
        $self->{_dateBegin} = $1;
        $self->{_dateEnd}   = $2;
    }
}

sub _dateFormat { ['eur'] }

sub _validateHeaderData {
    my $self = shift;

    # Do we want to do data validation for the header?

    die "Could not determine start and end date" unless ( $self->dateBegin );
    die "Could not determine discount rate"      unless ( $self->rDiscount );
    die "Could not determine currency code"      unless ( $self->currencyCode );
}

sub _isValidSaleRecord {
    my $self = shift;

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

    return $self->dateBegin && $self->rTitle;
}

sub _processLine {
    my $self  = shift;
    my $title = $self->rTitle();

    if ( $title && $title eq 'Net Total' ) {
        $self->{_endOfData} = 1;
    }

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

####
#     Data and Accessors
####

sub units        { 1 }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub formatType   { BookPub::DB::Item::Sale::kFormatTypeUnknownEBook }

sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->{_dateEnd} }
sub currencyCode  { shift->{_currency} }

sub rIsbn13 {
    my $self = shift;
    my $value = $self->_getByFieldName('rIsbn13') || return;

    $value =~ s/^isbn\s+//i;
    return $value;
}

1;
