package BookPub::Import::Importer::Gardners::Version14;

use strict;

use lib '/app/tools/bookpub/lib';
use lib '/app/tools/common/lib';

use Common::RSMath;

use base 'BookPub::Import::Importer';

sub _fieldMap {
    {
        dateBegin          => 'A',
        rTitle             => 'C',
        rIsbn13            => 'B',
        countryCode        => 'D',
        rUnits             => 'G',
        rListPrice         => 'H',
        rListPriceCurrency => 'E',
        rDiscount          => 'H2',
        rRevenue           => 'L',
        rChannel           => 'F2',
        rServiceName       => 'A1',
    };
}

sub _unverifiedFieldMap {
    { convertedListPrice => 'I', };
}

sub _headerIdentifier { ( rIsbn13 => 'EAN' ) }

sub _useIsSaleRec { 1 }

sub currencyCode { 'GBP' }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _isSaleRec { return shift->rIsbn13 }

sub rServiceName { return shift->_getByFieldName("rServiceName") =~ s/^(\w+).*$/$1/r }

sub _getDateBegin {
    my $self = shift;

    my $date = $self->SUPER::_getDateBegin;
    my ($fileMonth) = $self->filename =~ /(\d{2})20\d{2}/;

    # See if it's in m/d/yyyy format (not knowing which is m or d)
    my ( $first, $second, $year ) = $date =~ /^(\d+)\/(\d+)\/(\d{4})/;    # might have a trailing time we don't care about
    if ( !$year ) {
        ( $year, $first, $second ) = $date =~ /^(\d{4})-(\d{2})-(\d{2})$/    # better be yyyy-mm-dd then (again can't assume m/d)
    }

    if ( $first == $fileMonth ) {
        $date = sprintf( '%04d-%02d-%02d', $year, $first, $second );
    } elsif ( $second == $fileMonth ) {
        $date = sprintf( '%04d-%02d-%02d', $year, $second, $first );
    } else {

        # we'll just return whatever we found
    }

    return $date;
}

sub listPrice { return Common::RSMath::round( shift->_getByFieldName('convertedListPrice'), 2 ); }

sub revenue { return  shift->_getByFieldName('rRevenue'); }

1;

