package BookPub::Import::Importer::Follett::Version1;

use strict;

#use Data::Dumper;

#use lib '/app/tools/common/lib';
#use Common::Log;

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

# map of data columns
# Note:
#  - while there is a download date column, it contains some dates out of the intended
#  period of the file so parse the 'Year/Month' column instead
#
my %fieldMap = (
    date          => 0,
    isbn13        => 2,
    title         => 4,
    author        => 5,
    units         => 7,
    revenue       => 8,
    serviceProdID => 9,
);

#public methods

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

    my $lines = $args{lines};
    my $saleCount;

    # First, get the date from the first line.
    my ( $beginDate, $endDate ) = $self->_getDates( date_begin => $lines->[1][ $fieldMap{date} ], type => 'numerical_year_first' );

    for ( my $i = 1 ; $i <= scalar @$lines ; $i++ ) {
        my $line = $lines->[$i];

        #        Common::Log::Print("LINE: $i = " . Dumper($line));

        my $isbn13 = $line->[ $fieldMap{isbn13} ];
        next unless ( $isbn13 && length($isbn13) == 13 );

        my $title     = $line->[ $fieldMap{title} ];
        my $author    = $line->[ $fieldMap{author} ];
        my $units     = $line->[ $fieldMap{units} ];
        my $revenue   = $line->[ $fieldMap{revenue} ];
        my $svcProdID = $line->[ $fieldMap{serviceProdID} ];

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

        $saleRec->lineNum($i);

        # We don't store price anymore - But we do store _negative_ units
        # to signify a return.
        #
        if ( $revenue < 0 ) {
            $units *= -1;
        }

        $saleRec->dateBegin($beginDate);
        $saleRec->dateEnd($endDate);
        $saleRec->title($title);
        $saleRec->author($author);
        $saleRec->units($units);
        $saleRec->totalRevenue($revenue);
        $saleRec->isbn13($isbn13);
        $saleRec->serviceProductID($svcProdID);

        # defaults
        #
        $saleRec->currencyCode('USD');
        $saleRec->countryCode('US');
        $saleRec->productType(BookPub::DB::Item::Sale::kProductTypeBook);

        #                $saleRec->formatType(BookPub::DB::Item::Sale::kFormatTypeEBook);
        # !!! Just a temporary hack to test matching.
        #
        $saleRec->formatType(BookPub::DB::Item::Sale::kFormatTypeHardback);

        $saleRec->deliveryType(BookPub::DB::Item::Sale::kDeliveryTypeDownload);

        $self->_insertSale( sale => $saleRec );
        $saleCount++;
    }
    return $saleCount;
}

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