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

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';

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

    my %fieldMap = (
        3 => {
            dateBegin          => 'B',
            dateEnd            => 'C',
            priceType          => 'D',
            rAuthor            => 'H',
            rTitle             => 'G',
            rIsbn13            => 'F',
            rReturns           => 'J',
            rSales             => 'I',
            rUnits             => 'K',
            rListPrice         => 'L',
            rListPriceCurrency => 'E',
            rRevenue           => 'W',
            currencyCode       => 'U',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    my %fieldMap = (
        3 => {
            netProceeds => 'X',
        },
    );

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

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

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 _isSaleRec {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue');
    my $units   = $self->_getByFieldName('rUnits');

    # We're going to skip lines with no revenue and no units
    if ( $revenue == 0 && $units == 0 ) {
        return 0;
    }

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

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 countryCode {
    my $self     = shift;
    my $currency = $self->_getByFieldName('rListPriceCurrency');

    if ( $currency eq 'INR' ) {
        return 'IN';
    } else {
        $self->fail("Country code not set for list price currency: $currency");
    }

}

sub discount {
    my $self      = shift;
    my $units     = $self->units;
    my $listPrice = $self->listPrice;
    my $revenue   = $self->_getByFieldName('netProceeds');

    my $discount;

    if ($units) {
        $discount = 1 - ( $revenue / $units / $listPrice );
    }

    return $discount;
}

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