package BookPub::Import::Importer::Unizin;

use strict;

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

sub _headerIdentifier { ( rListPrice => 'List Price' ) }

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            dateBegin  => 'A',
            rTitle     => 'H',
            rIsbn13    => 'G',
            rUnits     => 'E',
            rUnitPrice => 'J',
            rListPrice => 'I',
            rRevenue   => 'K',
        },
        7 => {
            dateBegin  => 'A',
            rAuthor    => 'I',
            rTitle     => 'H',
            rIsbn13    => 'G',
            rUnits     => 'E',
            rUnitPrice => 'L',
            rListPrice => 'K',
            rRevenue   => 'M',
        },
        8 => {
            dateBegin  => 'A',
            rAuthor    => 'H',
            rTitle     => 'G',
            rIsbn13    => 'F',
            rUnits     => 'E',
            rUnitPrice => 'K',
            rListPrice => 'J',
            rRevenue   => 'L',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }
sub countryCode                { 'US' }
sub currencyCode               { 'USD' }
sub rListPriceCurrency         { 'USD' }

sub _isSaleRec {
    my $self = shift;

    my $dateBegin = $self->_getByFieldName('dateBegin');
    my $isbn      = $self->_getByFieldName('rIsbn13');
    my $title     = $self->_getByFieldName('rTitle');

    # We're going to skip the subtotal lines, which are blank for these fields
    if ( !$dateBegin && !$isbn && !$title ) {
        return 0;
    }

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

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

    # date is in quarters, 'Winter 2016'
    if ( $dateBegin =~ /(\w+) (\d{4})/ ) {
        if ( lc($1) eq 'spring' ) {
            return "Q1-$2";
        } elsif ( lc($1) eq 'summer' ) {
            return "Q2-$2";
        } elsif ( lc($1) eq 'fall' ) {
            return "Q3-$2";
        } elsif ( lc($1) eq 'winter' ) {
            return "Q4-$2";
        }
    }
    return $dateBegin;
}

sub _getDateEnd { return shift->_getDateBegin(); }

sub rInstitution {
    my $self = shift;

    my $institution;

    my $filename = $self->filename;

    if ( $filename =~ /^Sage (.+) \w+ \d{4}/i ) {
        $institution = $1;
    } elsif ( $filename =~ /^Bloomsbury US (.+) \w+ \d{4}/i ) {
        $institution = $1;
    }

    return $institution;
}

1;
