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

use strict;

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

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

    my %fieldMap = (
        13 => {
            priceType            => 'D',
            serviceProductID     => 'C',
            currencyCode         => 'Q1',
            countryCode          => 'L',
            rState               => 'K',
            dateBegin            => 'B',
            rProductType         => 'M',
            rFormat              => 'M',
            rIsbn13              => 'E',
            rTitle               => 'F',
            rSubtitle            => 'G',
            rAuthor              => 'H',
            rImprint             => 'I',
            rUnits               => 'O',
            rListPrice           => 'N',
            rListPriceCurrency   => 'N1',
            rDiscount            => 'P',
            rRevenue             => 'Q',
            rInstitution         => 'J',
            rChannel             => 'D',
            priceTypeQualifierID => 'D',
        },
        14 => {
            priceType          => 'D',
            serviceProductID   => 'C',
            currencyCode       => 'R1',
            countryCode        => 'L',
            rState             => 'K',
            dateBegin          => 'B',
            rProductType       => 'M',
            rFormat            => 'M',
            rIsbn13            => 'E',
            rTitle             => 'F',
            rSubtitle          => 'G',
            rAuthor            => 'H',
            rImprint           => 'I',
            rUnits             => 'P',
            rListPrice         => 'N',
            rListPriceCurrency => 'N1',
            rDiscount          => 'Q',
            rRevenue           => 'R',
            rInstitution       => 'J',
        },
        15 => {
            dateBegin          => 'B',
            rProductType       => 'M',
            rFormat            => 'M',
            priceType          => 'D',
            rAuthor            => 'H',
            rTitle             => 'F',
            rSubtitle          => 'G',
            rIsbn13            => 'E',
            rImprint           => 'I',
            rInstitution       => 'J',
            rState             => 'K',
            countryCode        => 'L',
            rUnits             => 'P',
            rListPrice         => 'N',
            rListPriceCurrency => 'N1',
            rDiscount          => 'R',
            rRevenue           => 'S',
            currencyCode       => 'S1',
            isPreOrder         => 'Q',
            rChannel           => 'D',
        },
        16 => {
            dateBegin          => 'B',
            rUnits             => 'O',
            rProductType       => 'M',
            rFormat            => 'M',
            priceType          => 'D',
            rAuthor            => 'H',
            rTitle             => 'F',
            rSubtitle          => 'G',
            rIsbn13            => 'E',
            rImprint           => 'I',
            rInstitution       => 'J',
            rState             => 'K',
            countryCode        => 'L',
            rListPrice         => 'N',
            rListPriceCurrency => 'N1',
            rDiscount          => 'Q',
            rRevenue           => 'R',
            currencyCode       => 'R1',
            isPreOrder         => 'P',
            rChannel           => 'D',
        },
        18 => {
            dateBegin                => 'A',
            rProductType             => 'L',
            rFormat                  => 'L',
            priceType                => 'C',
            rAuthor                  => 'G',
            rTitle                   => 'E',
            rSubtitle                => 'F',
            rIsbn13                  => 'D',
            rImprint                 => 'H',
            rInstitution             => 'I',
            rState                   => 'J',
            countryCode              => 'K',
            serviceProductID         => 'B',
            rUnits                   => 'O',
            rListPrice               => 'M',
            rListPriceCurrency       => 'M1',
            rNativeListPrice         => 'M',
            rNativeListPriceCurrency => 'M1',
            rDiscount                => 'P',
            rRevenue                 => 'Q',
            currencyCode             => 'Q1',
        },
    );

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

sub _headerIdentifier { rIsbn13 => 'ISBN' }
sub _useIsSaleRec     { 1 }
sub rServiceName      { 'OverDrive' }


sub purchaseType {
    my $self = shift;

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

    if ( $self->_version == 13 ) {
        if ( $rFormat =~ /^OverDrive\s(?:Read|Listen)$/i ) {
            return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
        } else {
            return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
        }
    }

    return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
}

sub priceTypeQualifierID {
    my $self = shift;

    my $type = $self->_getByFieldName('priceTypeQualifierID') || '';
    return unless $self->_version == 13;

    if ( $type =~ /^(?:Institutional - (?:Public|School) "?Library"?|Institutional - (?:Other|Academic))$/i ) {
        return BookPub::DB::Item::PriceTypeQualifier::kCorporate;    # library
    }

    return;
}

sub rUnits {
    my $self = shift;

    my $rUnits = $self->_getByFieldName('rUnits');
    return $rUnits;
}

sub rUnitPrice {
    my $self = shift;

    return $self->rUnits ? $self->rRevenue / $self->rUnits : 0;
}

sub priceType {
    my $self = shift;

    my $priceType = $self->_getByFieldName('priceType') || '';
    my $client = Common::RSApp::GetClientID();

    if ( $priceType =~ /^Retail$/i ) {
        return 'rrp';
    } elsif ( $priceType =~ /^Institutional - Public Library$/i ) {
        return 'rrp';
    } elsif ( $priceType =~ /^Institutional - School Library$/i ) {
        return 'agency+tax' if $client == 348 && $self->_version == 18; # MMAU
        return 'rrp';
    } elsif ( $priceType =~ /^Institutional - (?:Other|Academic)$/i ) {
        return 'rrp';
    }

    $self->fail( "Price type not set for " . $priceType );
}

sub currencyCode {
    my $self = shift;
    unless ( exists $self->{_currencyCode} ) {
        my $header = $self->_getByFieldName('currencyCode');
        $header =~ m/^Amt owed ([A-Z]{3})$/
          || $header =~ m/^Amt owed native ([A-Z]{3})$/
          || $self->fail("Unable to determine currency from header '$header'");
        $self->{_currencyCode} = $1;
    }
    return $self->{_currencyCode};
}

sub rListPriceCurrency {
    my $self = shift;
    unless ( exists $self->{_listPriceCurrency} ) {
        my $header = $self->_getByFieldName('rListPriceCurrency');
        $header =~ m/^SRP ([A-Z]{3})$/
          || $header =~ m/^SRP native ([A-Z]{3})$/
          || $self->fail("Unable to determine list price currency from header '$header'");
        $self->{_listPriceCurrency} = $1;
    }
    return $self->{_listPriceCurrency};
}

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

    return BookPub::DB::Item::Sale::kProductTypeAudioBook if ( $format =~ /audio/i );
    return BookPub::DB::Item::Sale::kProductTypeEBook     if ( $format =~ /ebook/i );
    return BookPub::DB::Item::Sale::kProductTypeEBook     if ( $format =~ /overdrive read/i );
    return BookPub::DB::Item::Sale::kProductTypeAudioBook if ( $format =~ /audio/i );
    return BookPub::DB::Item::Sale::kProductTypeAudioBook if ( $format =~ /overdrive listen/i );

    $self->fail( "Product type not set for " . $format );
}

sub formatType {
    my $self = shift;

    my $format = $self->_getByFieldName('rFormat') || return;

    if ( $self->_version == 13 ) {
        if ( $format =~ /^(?:Adobe EPUB eBook|Adobe PDF eBook|OverDrive Read)$/i ) {
            return BookPub::DB::Item::Sale::kProductTypeEBook;
        } elsif ( $format =~ /^(?:OverDrive MP3 Audiobook|OverDrive Listen)$/i ) {
            return BookPub::DB::Item::Sale::kProductTypeAudioBook
        }

        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 rFormat {
    my $self = shift;

    my $format = $self->_getByFieldName('rFormat') || '';
    return $format unless $self->_version == 13;

    if ( $format =~ /^(?:Adobe EPUB eBook|Adobe PDF eBook|OverDrive Read)$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    } elsif ( $format =~ /^(?:OverDrive MP3 Audiobook|OverDrive Listen)$/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook
    }

    return;
}

sub rState {
    my $self = shift;

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

    return $rState if $self->_version == 18;

    if ( $rState =~ /(\w{2})$/ ) {
        $rState = $1;
        if ( my $postal = Common::Postal->new( $self->countryCode() ) ) {
            if ( $postal->getName($rState) ) {

                # acceptable state abbreviation
                $state = $rState;
            }
        }
    }

    return $state;
}

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

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
        return $date;
    }

    return $date;
}

sub rNativeListPriceCurrency {
    my $self = shift;

    return unless $self->_version == 18;
    return $self->rListPriceCurrency();
}

sub isFree {
    my $self = shift;

    return 'N' if $self->_version !~ /^(?:16|18)$/;
    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

1;
