package BookPub::Import::Importer::INscribeDigital::Version3;

use strict;
use Data::Dumper;

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

# 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 => 'I',
            dateBegin   => 'B',
            dateEnd     => 'D',
            isbn        => 'H',
            rTitle      => 'G',
            rAuthor     => 'F',
            rUnits      => 'J',
            rListPrice  => 'K',
            rRevenue    => 'M',
        },
    };

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

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

my %summaryFieldMap = (
    firstColumn    => 0,
    conversionRate => 4,
);

my %conversionRates;
my $retailerName;

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' ) {
            foreach my $line (@$sheet) {

                my $firstColumn = $line->[ $summaryFieldMap{firstColumn} ];

                if ( $firstColumn =~ /iBookStore Retail Sales/ ) {
                    $retailerName = $firstColumn;
                }

                my $conversionRate = $line->[ $summaryFieldMap{conversionRate} ];

                if ($conversionRate) {
                    $conversionRates{$retailerName} = $conversionRate;
                }
            }
        }
    }
    Log->info( "conversionRates: " . Dumper(%conversionRates) );
}

sub conversionRate {
    my $self     = shift;
    my $retailer = $self->_getByFieldName('retailerName');

    my $conversionRate = $conversionRates{$retailer};

    return $conversionRate;
}

1;
