package BookPub::Import::Importer::BarnesNoble::Version1;

use strict;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::Sale;
use BookPub::Import::SaleRec;
use base 'BookPub::Import::Importer::BarnesNoble::Base';

# map of data columns
my %FIELD_MAP = (
    egift_date => 2,
    date       => 3,
    isbn13     => 4,
    units      => 5,
    ext_price  => 6,
    unit_price => 7,
    list_price => 8,
    imprint    => 11,
    author     => 14,
    title      => 15,
    is_agency  => 17,
);

#public methods

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

    my $lines     = $args{lines};
    my $saleCount = 0;
    my $skip      = 0;
    my ( $beginDate, $endDate );

    my $isAgency = _determineAgency($lines);

    for ( my $i = 1 ; $i < scalar @$lines ; $i++ ) {
        my $date = $lines->[$i][ $FIELD_MAP{egift_date} ];
        if ( !$date ) {
            $date = $lines->[$i][ $FIELD_MAP{date} ];
        }

        $beginDate = $endDate = Common::Util::normalize_date($date);
        my $isbn13    = $lines->[$i][ $FIELD_MAP{isbn13} ];
        my $units     = $lines->[$i][ $FIELD_MAP{units} ];
        my $unitPrice = $lines->[$i][ $FIELD_MAP{unit_price} ];
        my $listPrice = $lines->[$i][ $FIELD_MAP{list_price} ];
        my $imprint   = $lines->[$i][ $FIELD_MAP{imprint} ];
        my $author    = $lines->[$i][ $FIELD_MAP{author} ];
        my $title     = $lines->[$i][ $FIELD_MAP{title} ];

        unless ( $isbn13 or $title ) {
            $skip++;
            next;
        }
        $unitPrice =~ s/\s*\$//;
        $listPrice =~ s/\s*\$//;

        my $revenue = $units * $unitPrice;

        # subtitle, if it exists, is tacked onto the end of the remaining title
        my $subtitle;
        ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

        if ( $unitPrice < 0 ) {
            $unitPrice = abs($unitPrice);
            $units   *= -1 unless ( $units < 0 );
            $revenue *= -1 unless ( $revenue < 0 );
        }

        my $saleRec = BookPub::Import::SaleRec->new();

        # defaults
        $saleRec->countryCode('US');
        $saleRec->currencyCode('USD');
        $saleRec->productType(BookPub::DB::Item::Sale::kProductTypeEBook);
        $saleRec->formatType(BookPub::DB::Item::Sale::kFormatTypeEReader);
        $saleRec->purchaseType(BookPub::DB::Item::Sale::kPurchaseTypeDownload);

        if ($isAgency) {
            $saleRec->isAgency('Y');
        } else {
            $saleRec->isAgency('N');
        }

        $saleRec->lineNum( $i + 1 );
        $saleRec->dateBegin($beginDate);
        $saleRec->dateEnd($endDate);

        $saleRec->units($units);
        if ($listPrice) {
            $saleRec->listPrice($listPrice);
            $saleRec->discount( BookPub::Import::Importer::CalculateDiscount( $unitPrice, $listPrice ) );
        }
        $saleRec->unitPrice($unitPrice);
        $saleRec->revenue($revenue);

        $saleRec->rIsbn13($isbn13);
        $saleRec->rTitle($title);
        $saleRec->rSubtitle($subtitle) if $subtitle;
        $saleRec->rAuthor($author);
        $saleRec->rImprint($imprint);
        $saleRec->rUnits($units);
        $saleRec->rListPrice($listPrice);
        $saleRec->rUnitPrice($unitPrice);
        $saleRec->rRevenue($revenue);

        #$args{dumper}($saleRec);
        $self->_insertSale( sale => $saleRec );
        $saleCount++;
    }
    print STDERR "skipped $skip lines\n";

    return $saleCount;
}

sub _determineAgency {
    my $lines = shift;

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

    for ( my $i = 1 ; $i < scalar @$lines ; $i++ ) {
        if (   $lines->[$i][ $FIELD_MAP{isbn13} ]
            || $lines->[$i][ $FIELD_MAP{title} ] ) {
            $recs++;
            my ($unitPrice) = ( $lines->[$i][ $FIELD_MAP{unit_price} ] =~ m/^\s*-*\$*(\d*\.*\d+)\s*$/ );
            my ($listPrice) = ( $lines->[$i][ $FIELD_MAP{list_price} ] =~ m/^\s*-*\$*(\d*\.*\d+)\s*$/ );
            if ( $listPrice && $listPrice != 0 ) {
                $agencies++ if ( $unitPrice / $listPrice >= .65 );
            }
        }
    }

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

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