package BookPub::Import::Importer::WebCT::Version1;

use strict;

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, 0, 0 ],
    dataSheet     => 1,
    imprint       => 1,
    isbn10        => 2,
    altID1        => 4,
    serviceProdID => 5,
    title         => 7,
    units         => 14,
    revenue       => 17,
);

#public methods

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

    my $lines     = $args{sheets}->[ $fieldMap{dataSheet} ];
    my $saleCount = 0;

    # First, get the date from the first line of the first sheet.
    my ( $beginDate, $endDate ) = $self->_getDates(
        date_begin => $args{sheets}->[ $fieldMap{date}[0] ][ $fieldMap{date}[1] ][ $fieldMap{date}[2] ],
        type       => 'quarter'
    );

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

        my $isbn10  = $line->[ $fieldMap{isbn10} ];
        my $revenue = $line->[ $fieldMap{revenue} ];
        unless ( $revenue and $isbn10 and length($isbn10) == 10 ) {
            Common::Log::Print("skip line $i - revenue: '$revenue' isbn10: '$isbn10'");
            next;
        }

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

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

        $saleRec->lineNum($i);

        $saleRec->dateBegin($beginDate);
        $saleRec->dateEnd($endDate);
        $saleRec->imprint($imprint);
        $saleRec->title($title);
        $saleRec->units($units);
        $saleRec->totalRevenue($revenue);
        $saleRec->serviceProductID($svcProdID);
        $saleRec->isbn10($isbn10);
        $saleRec->altID1($altID1);

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

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

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