package BookPub::Import::Importer::Feedbooks::Version1;

use strict;
use warnings;

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

sub _fieldMap {
    {
        rServiceName       => 'BO',
        dateBegin          => 'E',
        dateEnd            => 'F',
        rFormat            => 'AD',
        rPriceType         => 'AK',
        rAuthor            => 'Y',
        rTitle             => 'X',
        rIsbn13            => 'U',
        rImprint           => 'AC',
        countryCode        => 'AL',
        rClientProductID   => 'W',
        rReturns           => 'AG',
        rSales             => 'AF',
        rUnits             => 'AH',
        rUnitPrice         => 'AM',
        rListPrice         => 'BQ',
        rListPriceCurrency => 'AO',
        rDiscount          => 'AP',
        rRevenue           => 'BC',
        currencyCode       => 'I',
    };
}

sub _unverifiedFieldMap {
    {
        saleDate => 'O',    #this field is currently unpopulated, but we'll import it and
                            #use it if it contains a valid date
    };
}

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

sub priceType                  { shift->rPriceType }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }

# The report begin and end dates are in colums E and F and will be used for dates
# if the "real" date isn't in column O, which it currently isn't.

sub _getDateBegin {
    my $self        = shift;
    my $reportBegin = $self->_getByFieldName('dateBegin') || return;
    my $saleDate    = $self->_getByFieldName('saleDate');

    # strip off the time stamp
    if ( $reportBegin && $reportBegin =~ /^(\d{4})(\d{2})(\d{2})$/ ) {
        return sprintf( "%04d-%02d-%02d", $1, $2, $3 );
    }

    return $saleDate;
}

sub _getDateEnd {
    my $self      = shift;
    my $reportEnd = $self->_getByFieldName('dateEnd') || return;
    my $saleDate  = $self->_getByFieldName('saleDate');

    # strip off the time stamp
    if ( $reportEnd && $reportEnd =~ /^(\d{4})(\d{2})(\d{2})$/ ) {
        return sprintf( "%04d-%02d-%02d", $1, $2, $3 );
    }

    return $saleDate;
}

sub priceType {
    my $self = shift;
    my $type = $self->_getByFieldName('rPriceType');

    if ( lc($type) eq 'agency' ) {
        return 'agency';
    } elsif ( lc($type) eq 'wholesale' ) {
        return 'rrp';
    } else {
        $self->fail("Unexpected priceType found: $type ");
    }
}

sub priceTypeQualifierID {
    my $self = shift;
    if ( $self->filename =~ /lib_sales/ ) {
        return BookPub::DB::Item::PriceTypeQualifier::kCorporate;    # Library sales
    } else {
        return undef;
    }
}

###
1;                                                                   # Play nicely.
###
