package BookPub::Import::Importer::INscribeDigital::Version2;

use strict;

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

sub _headerIdentifier { ( rTitle => 'TITLE' ) }

# We have to do some odd things with the field map here because this importer has
# different column definitions of seperate tabs.  The map is defined by tab name below.
# The summary tab is ignored here (returns and empty field set).
sub _fieldMap {
    my $self = shift;

    my $map = {
        'details' => {
            countryCode => 'H',
            dateBegin   => 'A',
            dateEnd     => 'C',
            isbn        => 'G',
            rTitle      => 'F',
            rAuthor     => 'E',
            rUnits      => 'I',
            rListPrice  => 'J',
            rRevenue    => 'L',
        },
    };

    # ignore all sheets except 'details'
    my $sheet = lc( $self->sheetname ) || return {};
    $sheet =~ /details/ ? return $map->{$sheet} : return {};
}

sub _unverifiedFieldMap {
    { retailerName => 'B', };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub currencyCode { 'USD' }

# This field map will only be used for the Summary tab
#
my %summaryFieldMap = (
    retailerName       => 0,
    conversionRate     => 4,
    altConversionRate  => 5,
    altConversionRate2 => 3,
);

my %conversionRates;

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        # We need to go through the summary tab and store the conversion rates
        #
        if ( lc($sheetname) ne 'payment' && lc($sheetname) ne 'details' ) {
            my $useAltConversionRate  = 0;
            my $useAltConversionRate2 = 0;
            foreach my $line (@$sheet) {

                # Trying to detect the exchange rate being shifted over one cell
                if ( $line->[ $summaryFieldMap{altConversionRate} ] eq 'EXCHANGE RATE' ) {
                    $useAltConversionRate = 1;
                } elsif ( $line->[ $summaryFieldMap{altConversionRate2} ] eq 'EXCHANGE RATE' ) {
                    $useAltConversionRate2 = 1;
                }

                my $conversionRate;

                if ( $useAltConversionRate == 1 ) {
                    $conversionRate = $line->[ $summaryFieldMap{altConversionRate} ];
                } elsif ( $useAltConversionRate2 == 1 ) {
                    $conversionRate = $line->[ $summaryFieldMap{altConversionRate2} ];
                } else {
                    $conversionRate = $line->[ $summaryFieldMap{conversionRate} ];
                }

                if ($conversionRate) {
                    my $retailerName = $line->[ $summaryFieldMap{retailerName} ];

                    # They've started adding "Total" to the service name.
                    # Let's strip that off here.
                    if ( $retailerName =~ /^(.*) Total$/ ) {
                        $retailerName = $1;
                    }
                    $conversionRates{$retailerName} = $conversionRate;
                }
            }

        }
    }

}

sub rRevenue {
    my $self         = shift;
    my $revenue      = $self->SUPER::rRevenue();
    my $retailerName = $self->_getByFieldName('retailerName');

    my $conversionRate = $conversionRates{$retailerName};

    if ( !$conversionRate ) {
        $self->fail("Unable to find conversion rate for $retailerName.");
        return undef;
    }

    $revenue *= $conversionRate;

    return $revenue;
}

1;
