package BookPub::Import::Importer::BarnesNoble::Version5;

use strict;
use Data::Dumper;

use lib '/app/tools/common/lib/';
use Common::Assert;

use lib '/app/tools/sale_import/lib/';
use Import::ValidationError;

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

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

sub _fieldMap {
    {
        dateBegin  => 'D',
        rIsbn13    => 'E',
        rTitle     => 'P',
        rSubtitle  => 'P',
        rAuthor    => 'O',
        rUnits     => 'F',
        rListPrice => 'I',
        rRevenue   => 'H',
    };
}

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

sub countryCode { 'US' }

sub currencyCode { 'USD' }

sub priceType { shift->{_priceType} }

sub productType { BookPub::DB::Item::Sale::kProductTypeEBook }

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub rListPriceCurrency { 'USD' }

sub _getDateBegin {
    my $self = shift;

    # We'll use the eGift Date if that column is populated.
    my $date = $self->_getByFieldName('eGiftDateBegin');

    if ( !$date ) {
        $date = $self->_getByFieldName('dateBegin');
    }

    return $date;
}

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

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

    # going to make our best guess as to whether this file contains agency model transactions.
    # we do that by looking at all transaction and if more than 75% of them return at least 65%
    # of the revenue back to the publisher, we'll assume (and i mean assume) they have an agency
    # agreement in place. Currently, agency deals are 70% of retail price and RRP typically 50%
    # of suggested retail. for historical reference, we started doing this because on 12/2/2011,
    # b & n stopped populating the "Order Type" column.

    my $isAgency;
    my $recs;
    my $agencies;
    my $priceType;

    # For Wiley, this file is always RRP.
    # We'll use the filename to support this exception to the rule.
    my $filename = $self->filename();
    if ( $filename =~ /23467_011905\.csv/ ) {
        $priceType = 'rrp';
    } else {
        foreach my $sheet ( @{ $args{sheets} } ) {
            foreach my $line (@$sheet) {

                # Since we're at the preProcess stage, it seems we have to reference rows by number.
                if ( $line->[4] || $line->[15] ) {
                    $recs++;
                    my ($unitPrice) = ( $line->[6] =~ m/^\s*-*\$*(\d*\.*\d+)\s*$/ );
                    my ($listPrice) = ( $line->[8] =~ m/^\s*-*\$*(\d*\.*\d+)\s*$/ );
                    if ( $listPrice && $listPrice != 0 ) {
                        $agencies++ if ( $unitPrice / $listPrice >= .65 );
                    }
                }
            }
        }

        $isAgency = ( $agencies / $recs ) >= .75;

        if ( $isAgency == 1 ) {
            $priceType = 'agency';
        } else {
            $priceType = 'rrp';
        }
    }

    $self->{_priceType} = $priceType;
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->SUPER::rRevenue();

    $revenue =~ s/,|\$//g;

    my $units = $self->units || 0;
    $units =~ s/,//g;

    if ( $revenue > 0 && $units < 0 ) {
        $self->fail("Positive revenue found with negative units");
        return undef;
    }

    if ( $revenue < 0 && $units > 0 ) {
        $self->fail("Negative revenue found with positive units");
        return undef;
    }

    return $revenue;
}

sub rListPrice {
    my $self = shift;

    my $listPrice = $self->SUPER::rListPrice();

    $listPrice =~ s/,|\$//g;

    return $listPrice;
}

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();

    if ( $title =~ /(.+):.+/ ) {
        $title = $1;
    }

    return $title;
}

sub rSubtitle {
    my $self = shift;

    my $title = $self->SUPER::rSubtitle();
    my $subtitle;

    if ( $title =~ /.+: (.+)/ ) {
        $subtitle = $1;
    }

    return $subtitle;
}

1;
