package BookPub::Import::Importer::OverDrive::Version9;

use strict;

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

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

sub _fieldMap {
    {
        countryCode  => 'C',
        rState       => 'C',
        dateBegin    => 'I',
        rProductType => 'D',
        rFormat      => 'D',
        rIsbn13      => 'E',
        rTitle       => 'B',
        rListPrice   => 'F',
        rRevenue     => 'G',
    };
}

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub currencyCode { 'USD' }
sub priceType    { 'rrp' }
sub units        { -1 }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin');
    if ( $date =~ /^(\d{2})\/(\d{2})\/(\d{4})/ ) {
        $date = $3 . "-" . $1 . "-" . $2;
    }

    return $date;
}

sub formatType {
    my $self = shift;
    my $format = $self->rFormat() || return;

    $format =~ /\s(\w+)\saudiobook/i;
    my $type = lc($1);

    if ( $self->productType eq BookPub::DB::Item::Sale::kProductTypeAudioBook ) {
        return $type;
    } else {
        return $self->_parseFormat($format);
    }
}

sub productType {
    my $self = shift;
    my $format = $self->rFormat() || return;

    return BookPub::DB::Item::Sale::kProductTypeAudioBook if ( $format =~ /audiobook/i );
    return BookPub::DB::Item::Sale::kProductTypeEBook     if ( $format =~ /ebook/i );

    return undef;
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');
    if ( $revenue > 0 ) {
        $revenue *= -1;
    }

    return $revenue;
}

sub countryCode {
    my $self        = shift;
    my $countryCode = $self->_getByFieldName('countryCode');
    my $state       = $self->rState();

    if ($state) {
        return 'US';
    } elsif ( $countryCode =~ /\((\w{2})\)$/ ) {
        $countryCode = $1;

        # Let's see if this is a valid country code.
        if ( Common::Country->Get($countryCode) ) {
            return $countryCode;
        }
    }

    # If we couldn't figure it out above, just default to US.
    return 'US';
}

sub rState {
    my $self  = shift;
    my $state = $self->_getByFieldName('rState');

    if ( $state =~ /\((\w{2})\)$/ ) {
        $state = $1;

        # Now, let's see if this is a US state code.
        my $postal = Common::Postal->new('US');

        if ( $postal->getName($state) ) {
            return $state;
        }

    }

    return undef;
}

1;
