package BookPub::Import::Importer::Zovio::Version3;

use strict;
use warnings;

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

sub _headerIdentifier { ( rAuthor => 'AuthorName' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        3 => {
            dateBegin          => 'N1',
            dateEnd            => 'N1',
            rAuthor            => 'F',
            rTitle             => 'C',
            rIsbn13            => 'D',
            rState             => 'K',
            rPostalCode        => 'L',
            countryCode        => 'J',
            rUnits             => 'N',
            rUnitPrice         => 'H',
            rListPriceCurrency => 'I',
            currencyCode       => 'I',
            rModel             => 'M',
        },
    );

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

sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType                  { 'rrp' }
sub rInstitution               { 'Zovio' }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }
sub rServiceName               { 'Zovio' }

sub rRevenue {
    my $self = shift;

    my $rUnitPrice = $self->rUnitPrice() || 0;
    my $units      = $self->units()      || 0;
    map { s/[^-?\d\.]//g } $rUnitPrice, $units;

    return $rUnitPrice * $units;
}

sub _getDateBegin {
    my $self      = shift;
    my $dateBegin = $self->_getByFieldName('dateBegin');

    if ( $dateBegin =~ /(\d{1,2})\.(\d{1,2})-\d{1,2}\.\d{1,2}\.(\d{4})/ ) {
        my $month = $1;
        my $day = $2, my $year = $3;

        $dateBegin = sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }

    return $dateBegin;
}

sub _getDateEnd {
    my $self    = shift;
    my $dateEnd = $self->_getByFieldName('dateEnd');

    if ( $dateEnd =~ /\d{1,2}\.\d{1,2}-(\d{1,2})\.(\d{1,2})\.(\d{4})/ ) {
        my $month = $1;
        my $day = $2, my $year = $3;

        $dateEnd = sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }

    return $dateEnd;
}

sub _processSheet {
    my ( $self, $sheet, $sheetnum ) = @_;

    return unless $self->{sheetname} =~ /^Total[s]?|ISBNs$/i;

    return $self->BookPub::Import::Importer::_processSheet( $sheet, $sheetnum );
}

sub rUnits {
    my $self = shift;

    my $rUnits = $self->_getByFieldName('rUnits') || 0;

    return $rUnits =~ /^[-+]?\d+$/ ? $rUnits : 0;
}

sub _isSaleRec {
    my $self = shift;

    my $rUnits = $self->_getByFieldName('rUnits') || 0;
    return if $rUnits =~ /^\*/;

    return $self->SUPER::_isSaleRec();
}

1;
