package BookPub::Import::Importer::Trajectory::v1;

use strict;

use Data::Dumper;
use POSIX;
use Date::Calc qw( Add_Delta_YMD );

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

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

sub _headerIdentifier { ( rIsbn13 => 'Main product ID#' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {

            # We're just going to use the dateEnd and use dateNormilzation to get the range for us.
            dateBegin          => 'F',
            rFormat            => 'T',
            priceType          => 'AC',
            rAuthor            => 'P',
            rTitle             => 'O',
            rIsbn13            => 'N',
            rImprint           => 'S',
            countryCode        => 'K',
            serviceProductID   => 'AP',
            rUnits             => 'X',
            rListPrice         => 'AB',
            rListPriceCurrency => 'AD',
            rDiscount          => 'AE',
            rRevenue           => 'AO',
            currencyCode       => 'I',
            rFee               => 'AN',
            rChannel           => 'M',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            subtotalCheck => 'A',
        },
    );

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

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

sub priceTypeID {
    my $self = shift;
    return $self->_getByFieldName('priceType');
}

sub _dateNormalization { 'month' }

sub _getDateBegin {
    my $self      = shift;
    my $dateBegin = $self->_getByFieldName('dateBegin');
    if ( $dateBegin =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
        my $year  = $1;
        my $month = $2;
        my $day   = $3;
        ( $year, $month, $day ) = Add_Delta_YMD( $year, $month, $day, 0, 0, -1 );
        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
    return $dateBegin;
}

sub _isSaleRec {
    my $self = shift;

    # We're going to check for the subtotal line.
    # Also going to skip the mysterious line that comes right after the header.
    my $subtotalCheck = $self->_getByFieldName('subtotalCheck');
    if ( $subtotalCheck =~ /Total Received$/i || $subtotalCheck =~ /Dang Dang$/i ) {
        return 0;
    }

    return $self->SUPER::_isSaleRec();
}

1;
