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

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Postal::US;

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

sub _fieldMap {
    {
        dateBegin      => 'B',
        dateEnd        => 'B',
        rAuthor        => 'L',
        rTitle         => 'K',
        rIsbn13        => 'N',
        rInstitution   => 'A',
        rUnits         => 'J',
        rUnitPrice     => 'Q',
        rListPrice     => 'P',
        rPurchasePrice => 'Q',
        rRevenue       => 'R',
    };
}

sub _headerIdentifier { rTitle => 'Title' }

sub _useIsSaleRec { 1 }

sub priceType              { 'rrp' }
sub purchaseType           { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rProductType           { BookPub::DB::Item::Sale::kProductTypeEBook }
sub productType            { shift->rProductType }
sub currencyCode           { 'USD' }
sub rListPriceCurrency     { 'USD' }
sub rPurchasePriceCurrency { 'USD' }

sub rServiceName { 'Unizin' }

sub rState {
    my $self  = shift;

    if ( my $state = $self->{_sheetname}{ $self->sheetname }{_rState} ) {
        return ucfirst $state;
    }

    $self->fail("Unable to determine state from sheetname: " . $self->sheetname);
}

sub countryCode {
    my $self = shift;

    return 'US' if $self->rState;

    $self->fail("Unable to determine country_code due to unrecognized state.");
}

sub _isSaleRec {
    my $self = shift;

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

    if ( !$dateBegin && !$isbn && !$title ) {
        return 0;
    }

    return 1;
}

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

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

    my $oPostalUS = Common::Postal::US->new();

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        while ( my($state, $abbr) = each %{ $oPostalUS->getAbbrList } ) {
            if ( $sheetname =~ /(:?\b$abbr\b|$state)/i ) {
                $self->{_sheetname}{$sheetname}{_rState} = $state;
            }
        }

    }

    return 1;
}


1;
