package BookPub::Import::Importer::EBook::Version12;

use strict;

use Data::Dumper;

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

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

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

sub _fieldMap {
    {
        countryCode        => 'N',
        dateBegin          => 'L',
        rFormat            => 'I',
        rIsbn13            => 'H',
        rTitle             => 'D',
        rAuthor            => 'E',
        rImprint           => 'C',
        rComments          => 'AC',
        rListPrice         => 'T',
        rListPriceCurrency => 'U',
        rDiscount          => 'AA',
        rState             => 'P',
        rPostalCode        => 'S',
    };
}

sub _unverifiedFieldMap {
    {
        eIsbn13          => 'G',
        coreCurrencyCode => 'U',
        saleCurrency     => 'A',
        exchangeRate     => 'C',
    };
}

# We have to read through the sheets before we process sales to find the conversion rates
# on the summary page.
sub _importLines {
    my $self        = shift;
    my %args        = @_;
    my $sheetNumber = 0;

    foreach my $sheet ( @{ $args{sheets} } ) {
        if ( $args{sheet_names}->[$sheetNumber] =~ /Summary/i ) {
            $self->_saveCurrency($sheet);
        }

        $sheetNumber++;
    }

    unless ( $self->conversionRates ) {
        $self->fail("Failed to read conversion rates from 'Summary' tab");
    }

    return $self->SUPER::_importLines(@_);
}

sub rRevenue {
    my $self      = shift;
    my $listPrice = $self->_getByFieldName('rListPrice');
    my $discount  = $self->_getByFieldName('rDiscount');
    my $revenue   = $listPrice * ( 1 - ( $discount / 100 ) );
    return $revenue;
}

sub rListPrice {
    my $self      = shift;
    my $listPrice = $self->_getByFieldName('rListPrice');
    return abs($listPrice);
}

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

    $self->fail("Unknown core currency") unless ($coreCurrencyCode);

    $coreCurrencyCode = substr $coreCurrencyCode, 0, 3;

    my $exchangeRate = $self->conversionRates->{$coreCurrencyCode};

    $self->fail("Unable to determine conversion rate for '$coreCurrencyCode'")
      unless ($exchangeRate);

    return $exchangeRate == 1 ? $revenue : $revenue * $exchangeRate;
}

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

    return $priceType =~ m/Agency/i ? 'agency' : 'rrp';
}

sub isFree {
    my $self  = shift;
    my $price = $self->_getByFieldName('rListPrice');

    return $price eq 0 ? 'Y' : 'N';
}

sub rIsbn13 {
    my $self = shift;
    my $isbn = $self->_getByFieldName('rIsbn13');

    my $eisbn = $self->_getByFieldName('eIsbn13');

    if ( defined($isbn) && $isbn ne '' ) {
        return $isbn;
    } else {
        return $eisbn;
    }
}

sub _isValidSaleRecord {
    my $self    = shift;
    my $eIsbn13 = $self->_getByFieldName('eIsbn13');

    return $self->rTitle && ( $self->rIsbn10 || $self->rIsbn13 || $eIsbn13 || $self->rRevenue ) && $self->dateBegin;
}

sub units {
    my $revenue = shift->rRevenue || return 1;
    return $revenue < 0 ? -1 : 1;
}

sub _saveCurrency {
    my $self = shift;
    my $sheet = shift || return;

    my $saleCurrency;
    my $exchangeRate;

    $self->{_conversionRates} = {};

    foreach my $line (@$sheet) {
        $self->{line} = $line;
        $saleCurrency = $self->_getByFieldName('saleCurrency');
        $exchangeRate = $self->_getByFieldName('exchangeRate');

        Log->debug("C: $saleCurrency E: $exchangeRate");
        if ( $saleCurrency && $exchangeRate && $saleCurrency =~ /^\w{3}$/ && $exchangeRate =~ /^[\d\.]+$/ ) {
            $self->{_conversionRates}->{$saleCurrency} = $exchangeRate;
        }
    }

    return unless ( $self->conversionRates );

    # Lets validate that our sales are reported in USD
    unless ( $self->conversionRates->{USD} ) {
        $self->fail("Conversion rate not found for 'USD'");
    }

    unless ( $self->conversionRates->{USD} == 1 ) {
        $self->fail("Sale file appears to be reported in currency other than USD");
    }

    return $self->conversionRates();
}

sub conversionRates { shift->{_conversionRates} }

1;
