package BookPub::Import::Importer::Librify;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

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

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rPriceType         => 'X',
            currencyCode       => 'I',
            countryCode        => 'V',
            dateBegin          => 'K',
            rIsbn13            => 'M',
            rTitle             => 'N',
            rAuthor            => 'O',
            rSales             => 'R',
            rReturns           => 'S',
            rListPrice         => 'W',
            rListPriceCurrency => 'Y',
            rDiscount          => 'Z',
            rRevenue           => 'AD',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

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

    if ( $date && ( $date =~ /(\d{4})-?(\d{2})-?(\d{2})/ ) ) {
        my ( $year, $month, $day ) = ( $1, $2, $3 );
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    } else {
        $self->fail( "Couldn't determine date from: " . $date );
    }
}

sub priceType {
    my $self = shift;
    my $type = lc( $self->rPriceType ) || return;

    if ( $type == 41 || $type == 43 ) {
        $type = 'agency';
    } elsif ( $type == 6 ) {
        $type = 'rrp';
    }

    return $type;
}

1;
