package BookPub::Import::Importer::Apple::Version1;

use strict;

use Date::Calc qw(Days_in_Month);
use Data::Dumper;

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

use lib '/app/tools/data_classes/lib';

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

# map version number to data columns
my %_fieldMap = (
    'start_date'         => 0,
    'end_date'           => 1,
    'vendor_id'          => 4,
    'units'              => 5,
    'unit_price'         => 6,
    'net_revenue'        => 7,
    'currency_code'      => 8,
    'sales_return_flag'  => 9,
    'apple_id'           => 10,
    'author'             => 11,
    'title'              => 12,
    'imprint'            => 13,
    'product_type_id'    => 15,
    'country_code'       => 17,
    'promo'              => 19,
    'list_price'         => 20,
    'orig_currency_code' => 21,
);

sub _getFieldMap {
    my ($self) = @_;

    return \%_fieldMap;
}

sub _getColumnValue {
    my ( $self, $line, $colName ) = @_;

    my $fieldMap = $self->_getFieldMap();
    return undef unless defined $fieldMap->{$colName};
    return $line->[ $fieldMap->{$colName} ];
}

#public methods

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

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

    my $fieldMap = $self->_getFieldMap();

    # Just skip the first line:  It's the header.
    for ( my $i = 1 ; $i < scalar @$lines ; $i++ ) {
        my $line = $lines->[$i];

        my $dateBegin      = $self->_getColumnValue( $line, 'start_date' );
        my $dateEnd        = $self->_getColumnValue( $line, 'end_date' );
        my $vendorID       = $self->_getColumnValue( $line, 'vendor_id' );
        my $units          = $self->_getColumnValue( $line, 'units' );
        my $unitPrice      = $self->_getColumnValue( $line, 'unit_price' );
        my $netRevenue     = $self->_getColumnValue( $line, 'net_revenue' );
        my $currencyCode   = $self->_getColumnValue( $line, 'currency_code' );
        my $saleReturnFlag = $self->_getColumnValue( $line, 'sales_return_flag' );
        my $appleID        = $self->_getColumnValue( $line, 'apple_id' );
        my $author         = $self->_getColumnValue( $line, 'author' );
        my $title          = $self->_getColumnValue( $line, 'title' );
        my $imprint        = $self->_getColumnValue( $line, 'imprint' );
        my $productTypeID  = $self->_getColumnValue( $line, 'product_type_id' );
        my $countryCode    = $self->_getColumnValue( $line, 'country_code' );
        my $promoCode      = $self->_getColumnValue( $line, 'promo' );
        my $listPrice      = $self->_getColumnValue( $line, 'list_price' );

        # not using this yet
        #my $origCurrencyCode    = $self->_getColumnValue($line, 'orig_currency_code');

        my $formatType = $self->_parseProductTypeID($productTypeID);

        # 'isbn' comes out of the 'Vendor Identifier' column.  It can be either an
        # isbn10 or an isbn13, with or without spaces.
        #
        my ( $isbn10, $isbn13 ) = $self->_parseVendorIdentifier($vendorID);
        next unless ( $isbn10 || $isbn13 );

        my $begin = Common::Date->new($dateBegin);
        my $end   = Common::Date->new($dateEnd);

        my $beginDate = $begin->asString();
        my $endDate   = $end->asString();

        unless ( $beginDate and $endDate ) {
            $self->errstr('invalid dates');
            Common::Log::Print("invalid dates: $dateBegin - $dateEnd ($i)");
            next;
        }

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

        # defaults
        $saleRec->productType(BookPub::DB::Item::Sale::kProductTypeEBook);
        $saleRec->purchaseType(BookPub::DB::Item::Sale::kPurchaseTypeDownload);
        $saleRec->isAgency('Y');
        $saleRec->lineNum( $i + 1 );

        $saleRec->dateBegin($beginDate);
        $saleRec->dateEnd($endDate);

        $saleRec->formatType($formatType);
        $saleRec->serviceProductID($appleID);

        $saleRec->units($units);
        $saleRec->unitPrice($unitPrice);
        $saleRec->listPrice( abs($listPrice) );
        $saleRec->discount( BookPub::Import::Importer::CalculateDiscount( $unitPrice, $listPrice ) );
        $saleRec->revenue($netRevenue);
        $saleRec->currencyCode($currencyCode);
        $saleRec->countryCode($countryCode);

        $saleRec->rFormat($productTypeID);
        $isbn13 ? $saleRec->rIsbn13($isbn13) : $saleRec->rIsbn10($isbn10);
        $saleRec->rTitle($title);
        $saleRec->rAuthor($author);
        $saleRec->rImprint($imprint);
        'R' eq $saleReturnFlag ? $saleRec->rReturns( abs($units) ) : $saleRec->rSales($units);
        $saleRec->rUnitPrice($unitPrice);
        $saleRec->rListPrice($listPrice);
        $saleRec->rRevenue($netRevenue);
        $saleRec->rPromoCode($promoCode) if $promoCode;

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

    return $saleCount;
}

sub _parseVendorIdentifier {
    my ( $self, $vendorID ) = @_;

    my ( $isbn10, $isbn13 );

    # Strip out any non alpha-numeric characters ('-', typically)
    #
    $vendorID =~ s/\W//g;

    if ( 10 == length($vendorID) ) {
        $isbn10 = $vendorID;
    } elsif ( 13 == length($vendorID) ) {
        $isbn13 = $vendorID;
    }

    return ( $isbn10, $isbn13 );
}

sub _parseProductTypeID {
    my ( $self, $productTypeID ) = @_;

    if (   '1' eq $productTypeID
        || 'IA1' eq $productTypeID ) {
        return BookPub::DB::Item::Sale::kFormatTypeAppleMultimedia;
    }

    return BookPub::DB::Item::Sale::kFormatTypeUnknownEBook;
}

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