package BookPub::Import::Importer::ScrollMotion::ScrollMotion1;

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

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

    my $fieldMap = $self->_getFieldMap();
    my $lines    = $args{lines};
    my $saleCount;

    my $dateStr = $lines->[ $fieldMap->{date}[0] ][ $fieldMap->{date}[1] ];
    $dateStr =~ s/\s*$//;
    $dateStr =~ s/^.*\s(\w+\s\d+)$/$1/;
    my ( $dateBegin, $dateEnd ) = $self->_getDates( date_begin => $dateStr );
    unless ( $dateBegin and $dateEnd ) {
        $self->errstr('invalid date');
        Common::Log::Print("invalid date string: '$dateStr'");
        return undef;
    }

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

    my %errMsg = ();
    for ( my $i = 2 ; $i < scalar @$lines ; $i++ ) {
        my $titleTmp = $lines->[$i][ $fieldMap->{title} ];
        my $isbn13   = $lines->[$i][ $fieldMap->{isbn13} ];
        unless ( $titleTmp or $isbn13 ) {
            Common::Log::Print("skip line $i - title: '$titleTmp', isbn: '$isbn13'");
            next;
        }

        my $units     = $lines->[$i][ $fieldMap->{units} ];
        my $listPrice = $lines->[$i][ $fieldMap->{listPrice} ];
        my $discount  = $lines->[$i][ $fieldMap->{discount} ];
        my $revenue   = $lines->[$i][ $fieldMap->{revenue} ];
        my $country   = defined $fieldMap->{country} ? $lines->[$i][ $fieldMap->{country} ] : 'US';
        my $currency  = defined $fieldMap->{currency} ? $lines->[$i][ $fieldMap->{currency} ] : 'USD';
        my $format    = $lines->[$i][ $fieldMap->{format} ];

        my $formatType =
          $format =~ /mobile phone application/i
          ? BookPub::DB::Item::Sale::kFormatTypeAppleMultimedia
          : '';
        unless ($formatType) {
            $self->errstr( 'unknown format: ' . $format );
            unless ( $errMsg{$format} ) {
                Common::Log::Print("unknown format: $format ($i)");
            }
            $errMsg{$format} = 1;
        }

        # why create a separate col when you can stuff more values into the ones
        # you already have?

        # author is _usually_ tacked onto the end of title
        my ( $title, $author ) = $titleTmp =~ m/^(.+?)\s+by\s+(.+)$/i;
        $title ||= $titleTmp;

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

        # free or preview is tacked onto the end of the isbn (if free)
        $isbn13 =~ s/(\D+)$//;

        #my $extra = $1; # not saving anywhere in db yet

        my $freeFlag  = 0;
        my $promoCode = '';
        my $unitPrice;
        if ( $revenue == 0 ) {
            $freeFlag = 1;
            if ( $title =~ m/preview/i ) {

                # perhaps no need to save this until they have something other than 'preview'
                $promoCode = 'preview';
                $title =~ s/\spreview a.*?$//i or $title =~ s/\sexclusive free preview//i;
            }
        } else {
            $unitPrice = abs( $revenue / $units ) if ( $units != 0 );
        }

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

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

        $saleRec->lineNum( $i + 1 );
        $saleRec->dateBegin($dateBegin);
        $saleRec->dateEnd($dateEnd);
        $saleRec->isFree('Y') if $freeFlag;

        $saleRec->isAgency($agency);
        $saleRec->formatType($formatType);
        $saleRec->units($units);
        $saleRec->listPrice($listPrice);
        if ($unitPrice) {
            $saleRec->discount( BookPub::Import::Importer::CalculateDiscount( $unitPrice, $listPrice ) );
            $saleRec->unitPrice($unitPrice);
        }
        $saleRec->revenue($revenue);
        $saleRec->currencyCode( $currency || 'USD' );
        $saleRec->countryCode( $country   || 'US' );

        $saleRec->rFormat($format);
        $saleRec->rIsbn13($isbn13);
        $saleRec->rTitle($title);
        $saleRec->rSubtitle($subtitle) if $subtitle;
        $saleRec->rAuthor($author);
        $saleRec->rUnits($units);
        $saleRec->rListPrice($listPrice);
        $saleRec->rDiscount($discount);
        $saleRec->rRevenue($revenue);
        $saleRec->rPromoCode($promoCode) if $promoCode;

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

    return $saleCount;
}

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