package BookPub::Import::Importer::Flipkart::Version1;

use strict;

use lib '/app/tools/common/lib';
use Common::Country;
use Data::Dumper;

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

sub _fieldMap {
    {
        # header
        currencyCode => 'BQ',

        #detail
        priceType          => 'H',
        countryCode        => 'K',
        dateBegin          => 'E',
        dateEnd            => 'F',
        isbn               => 'U',
        rTitle             => 'X',
        rAuthor            => 'Y',
        rUnits             => 'BG',
        rSales             => 'BE',
        rReturns           => 'BF',
        rListPrice         => 'AM',
        rListPriceCurrency => 'AO',
        rRevenue           => 'BQ',
    };
}

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

sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _dateFormat                { [ 'numerical_year_first', 'iso' ] }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }

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

    if ( $type == 1 || $type == 2 ) {
        return 'rrp';
    } else {
        $self->fail( "Unknown priceType in column H " . $type );
    }

}

sub _processHeader {
    my $self = shift;

    # currency code is in the header, sometimes.  If it's not present and it's a
    # BloomsburyWW file, default to GBP.  If not, we'll error out
    my $currency;
    my $header = $self->_getByFieldName('currencyCode');

    $header =~ m/\(([A-Z]{3})\)$/;    # looking for something like (USD)
    if ($1) {
        $currency = "$1";
    }

    if ( Common::CurrencyFormat::CodeIsValid($currency) ) {
        $self->{_currencyCode} = $currency;
    } elsif ( Common::RSApp::GetClientID() == 328 ) {    # Bloomsbury World Wide
        $self->{_currencyCode} = 'GBP';
    } else {
        $self->fail( "Couldn't determine currencyCode " . "in header column BQ " . $header );
    }
}

sub currencyCode {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $isbn      = $self->_getByFieldName('isbn');
    my $title     = $self->_getByFieldName('rTitle');
    my $author    = $self->_getByFieldName('rAuthor');
    my $priceType = $self->_getByFieldName('priceType');

    # We're going to skip the subtotal lines, which are blank for these fields
    if ( !$dateBegin && !$isbn && !$title && !$author && !$priceType ) {
        return 0;
    }

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

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