package BookPub::Import::Importer::SharedBook;

use strict;

use Date::Calc qw(Decode_Month);

use lib '/app/tools/bookpub/lib';
use base 'BookPub::Import::Importer';

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( rIsbn13 => 'Item Code' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rIsbn13      => 1, #B
            rTitle       => 0, #A
            rUnits       => 3, #D
            rListPrice   => 2, #C
            rRevenue     => 4, #E
            rInstitution => 0, #A
        },
    );

    return $fieldMap{ $self->_version() };
}

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

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    foreach my $sheet ( @{ $args{sheets} } ) {
        foreach my $line (@$sheet) {

            # Since we're at the preProcess stage, it seems we have to reference rows by number.
            my $dateCell = $line->[0];
            if ( $dateCell =~ m/(\w+) (\d{1,2}), (\d{4}) through (\w+) (\d{1,2}), (\d{4})/i ) {
                my $dateBeginMonth = Decode_Month($1);
                my $dateBeginDay   = $2;
                my $dateBeginYear  = $3;

                my $dateEndMonth = Decode_Month($4);
                my $dateEndDay   = $5;
                my $dateEndYear  = $6;

                $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $dateBeginYear, $dateBeginMonth, $dateBeginDay );
                $self->{_dateEnd}   = sprintf( "%04d-%02d-%02d", $dateEndYear,   $dateEndMonth,   $dateEndDay );
                last;
            }
        }
        if ( !$self->{_dateBegin} || !$self->{_dateEnd} ) {
            $self->fail("Unable to find date in header");
        }
    }
}

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

    my $dateBegin = $self->{_dateBegin};
    my $dateEnd   = $self->{_dateEnd};

    my $fieldMapRef = $self->_fieldMap();

    my %fieldMap = %$fieldMapRef;

    my $lines = $args{sheets}[ $fieldMap{dataSheet} ];
    for ( my $i = 6 ; $i < scalar @$lines ; $i++ ) {
        my $title       = $lines->[$i][ $fieldMap{rTitle} ];
        my $institution = $lines->[$i][ $fieldMap{rInstitution} ];
        my $isbn13      = $lines->[$i][ $fieldMap{rIsbn13} ];
        my $listPrice   = $lines->[$i][ $fieldMap{rListPrice} ];
        my $units       = $lines->[$i][ $fieldMap{rUnits} ]   || 0;
        my $revenue     = $lines->[$i][ $fieldMap{rRevenue} ] || 0;

        # Store the title and move on.
        if ( $title =~ /^Book Title:\s?(.*)$/i ) {
            $self->{_title} = $1;
            next;
        }

        # Store the institution and move on.
        if ( $institution =~ /^School:\s?(.*)$/i ) {
            $self->{_institution} = $1;
            next;
        }

        # Skip lines we don't care about.
        if ( uc($title) eq 'TOTAL' || $title =~ /^Course Pack Title:/i ) {
            next;
        }

        # Skip blank lines.
        unless ( $self->{_title} && $self->{_institution} && $isbn13 && ($units || $revenue) ) {
            next;
        }

        # !!! Note that we are going to overwrite the title data right here
        # !!! with the value that was stored earlier.
        my $subtitle;
        ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle( $self->{_title} );

        if ( $isbn13 =~ /-(\d{13})_/i ) {
            $isbn13 = $1;
        }

        my $unitPrice;
        if ( $units != 0 ) {
            $unitPrice = $revenue / $units;
        }

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

        # defaults
        $saleRec->countryCode('US');
        $saleRec->currencyCode('USD');
        $saleRec->rServiceName('XanEdu');
        $saleRec->priceTypeID(BookPub::DB::Item::PriceType::kPriceTypeRRP);
        $saleRec->productType(BookPub::DB::Item::Sale::kProductTypeEBook);
        $saleRec->rProductType(BookPub::DB::Item::Sale::kProductTypeEBook);
        $saleRec->purchaseType(BookPub::DB::Item::Sale::kPurchaseTypeDownload);
        $saleRec->lineNum( $i + 1 );

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

        $saleRec->rIsbn13($isbn13);
        $saleRec->rTitle($title);
        $saleRec->rSubtitle($subtitle) if $subtitle;
        $saleRec->rListPrice($listPrice);
        $saleRec->listPrice($listPrice);
        $saleRec->unitPrice($unitPrice);
        $saleRec->rUnits($units);
        $saleRec->units($units);
        $saleRec->rRevenue($revenue);
        $saleRec->revenue($revenue);
        $saleRec->rInstitution( $self->{_institution} );
        $saleRec->rTitle( $self->{_title} );

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

    return $saleCount;
}

1;
