package BookPub::Import::Importer::Kobo::Kobo1;

use strict;

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

# currently, agency model type sales are not mixed with non-agency sales so the 'agency' flag can be
# set at a file level.  override _isAgency in the subclass if it IS an agency model file
sub _isAgency { return 'N'; }

#public methods

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

    my %errMsg = ();
    my $saleCount;
    my $lineNumBase = scalar $args{sheets} > 1 ? 100000 : 0;
    my $sheetIndex = 0;

    # in case they leave out a date (which DOES happen), determine the month range so we
    # can default to month/start - month/end
    # use the 2nd sheet since that has always been a non-summary sheet
    my $sampleSheet = $args{sheets}[1];
    my ( $fMap, $junk ) = $self->_getFieldMap( $sampleSheet->[1], $args{sheet_names}[1] );
    my ( $dateBegin, $dateEnd );
    my $i = 1;
    while ( defined $sampleSheet->[$i] ) {
        ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $sampleSheet->[$i][ $fMap->{date} ] );
        last if ( $dateBegin && $dateEnd );
        $i++;
    }
    Common::Log::Print("default date range: $dateBegin, $dateEnd");

    my $agency = $self->_isAgency();

    foreach my $lines ( @{ $args{sheets} } ) {
        my $sign         = 1;    # primarily used to make revenue negative for the 'Refunds' sheet
        my $unitsDefault = 0;    # value to use for units when not supplied ('Refunds' sheet)

        if ( $args{sheet_names}[$sheetIndex] =~ m/summary/i ) {
            Common::Log::Print("skip sheet '$args{sheet_names}[$sheetIndex]'");
            next;
        } elsif ( $args{sheet_names}[$sheetIndex] =~ m/refund/i ) {
            $unitsDefault = -1;
            $sign         = -1;
        }

        # pass the first data row (or any non-header row) followed by the sheet name
        my ( $fieldMap, $currencyDefault ) = $self->_getFieldMap( $lines->[1], $args{sheet_names}[$sheetIndex] );

        my $lineNum = 1 + $lineNumBase * ( $sheetIndex + 1 );
        for ( my $i = 1 ; $i < scalar @$lines ; $i++ ) {
            $lineNum += $i;
            my $units  = defined $fieldMap->{units} ? $lines->[$i][ $fieldMap->{units} ] : 0;
            my $title  = $lines->[$i][ $fieldMap->{title} ];
            my $isbn13 = $lines->[$i][ $fieldMap->{isbn13} ];
            $isbn13 =~ s/\D+//g;    # some version contain some decoration
            unless ( ( $units || $unitsDefault ) && ( $title || ( $isbn13 and $isbn13 =~ m/^\d+$/ ) ) ) {
                Common::Log::Print("skip line $lineNum - units: '$units', title: '$title', isbn: '$isbn13'");
                next;
            }

            $units ||= $unitsDefault;

            # sux we gotta perform this check, but at least once i saw a non-unit string in the units col
            unless ( $units =~ m/^\-?\d+$/ ) {
                $self->errstr("invalid units line $lineNum");
                Common::Log::Print("skip line $lineNum - invalid units: $units");
                next;
            }

            my $dateTmp   = $lines->[$i][ $fieldMap->{date} ];
            my $country   = $lines->[$i][ $fieldMap->{country} ];
            my $author    = $lines->[$i][ $fieldMap->{author} ];
            my $listPrice = $lines->[$i][ $fieldMap->{listPrice} ];
            my $discount  = defined $fieldMap->{discount} ? $lines->[$i][ $fieldMap->{discount} ] : '';
            my $revenue   = $lines->[$i][ $fieldMap->{revenue} ];
            my $currency  = $lines->[$i][ $fieldMap->{currency} ] || $currencyDefault;
            $currency ||= 'USD' unless ($revenue);

            my $unitPrice = abs( $revenue / $units );    # units has always been non-zero

            $revenue *= $sign;

            my $date = $dateTmp ? Common::Util::normalize_date($dateTmp) : '';

            my $countryCode = $country =~ m/^[A-Z]{2}$/ ? $country : $Common::Consts::COUNTRY_CODE{ lc $country };
            unless ($countryCode) {
                $self->errstr("unknown country: $country");
                unless ( $errMsg{$country} ) {
                    Common::Log::Print("unknown country '$country' ($lineNum)");
                    $errMsg{$country} = 1;
                }
            }

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

            # defaults
            $saleRec->formatType(BookPub::DB::Item::Sale::kFormatTypeUnknownEBook);
            $saleRec->productType(BookPub::DB::Item::Sale::kProductTypeEBook);
            $saleRec->purchaseType(BookPub::DB::Item::Sale::kPurchaseTypeDownload);
            $saleRec->lineNum($lineNum);

            $saleRec->dateBegin( $date || $dateBegin );
            $saleRec->dateEnd( $date   || $dateEnd );

            $saleRec->isAgency($agency);
            $saleRec->units($units);
            $saleRec->listPrice($listPrice);
            $saleRec->discount( BookPub::Import::Importer::CalculateDiscount( $unitPrice, $listPrice ) ) if $listPrice;
            $saleRec->unitPrice($unitPrice);
            $saleRec->revenue($revenue);
            $saleRec->currencyCode($currency);
            $saleRec->countryCode($countryCode);

            $saleRec->rIsbn13($isbn13);
            $saleRec->rTitle($title);
            $saleRec->rAuthor($author);
            $saleRec->rUnits($units);
            $saleRec->rListPrice($listPrice);
            $saleRec->rDiscount( 1 - $discount ) if ($discount);

            #$args{dumper}($saleRec);
            $self->_insertSale( sale => $saleRec );
            $saleCount++;
        }
    } continue    # sheet loop
    {
        $sheetIndex++;
    }

    return $saleCount;
}

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