package BookPub::Import::Importer::Glose;

use strict;
use warnings;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( rIsbn13 => 'ISBN' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            currencyCode           => 'O',
            countryCode            => 'F',
            rPostalCode            => 'G',
            dateBegin              => 'B',
            rIsbn13                => 'A',
            rTitle                 => 'E',
            rAuthor                => 'D',
            rUnits                 => 'C',
            rListPrice             => 'K',
            rPurchasePrice         => 'M',
            rPurchasePriceCurrency => 'J',
            rTaxUnitPrice          => 'N',
            rRevenue               => 'P',

        },
        2 => {
            dateBegin              => 'D',
            rFormat                => 'C',
            rAuthor                => 'F',
            rTitle                 => 'G',
            rIsbn13                => 'B',
            rState                 => 'I',
            rPostalCode            => 'J',
            countryCode            => 'H',
            rUnits                 => 'E',
            rListPrice             => 'N',
            rPurchasePrice         => 'P',
            rPurchasePriceCurrency => 'M',
            rDiscount              => 'T',
            rRevenue               => 'S',
            currencyCode           => 'R',
            rTaxAmount             => 'Q',
            rTaxUnitPrice          => 'O',
        },
        3 => {
            dateBegin              => 'D',
            rProductType           => 'C',
            rAuthor                => 'F',
            rTitle                 => 'G',
            rIsbn13                => 'B',
            rState                 => 'I',
            rPostalCode            => 'J',
            countryCode            => 'H',
            rUnits                 => 'E',
            rListPrice             => 'N',
            rPurchasePrice         => 'P',
            rPurchasePriceCurrency => 'M',
            rDiscount              => 'T',
            rRevenue               => 'N',
            currencyCode           => 'R',
            rTaxAmount             => 'Q',
            rTaxUnitPrice          => 'O',
        }
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub rServiceName               { 'Glose' }
sub rProductType               { shift->productType }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceType                  { shift->_version == 3 ? 'rrp' : 'agency' }
sub discount {
    my $self = shift;

    return unless ($self->_version == 2 || $self->_version == 3);
    return 1 - $self->rDiscount;
}

sub _getDateBegin {
    my $self = shift;

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

    #YYYYMMDD
    if ( $date =~ /(\d{4})[-\/]?(\d{2})[-\/]?(\d{2})/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, $3;
    }
    # M/D/YYYY or M/DD/YYYY
    elsif ( $date =~ /(\d{1,2})[-\/]?(\d{1,2})[-\/]?(\d{4})/ ) {
        return sprintf "%04d-%02d-%02d", $3, $1, $2;
    }
    # MM/DD/YY
    elsif ( $date =~ /(\d{1,2}).(\d{1,2}).(\d{2})/ ) {
        return sprintf "20%02d-%02d-%02d", $3, $1, $2;
    }

    $self->fail("Unable to determine date begin from: '$date'");
}

sub productType {
    my $self = shift;

    my $clientID = Common::RSApp::GetClientID();
    my $version = $self->_version;

    if ( $version == 3 ) {
        my $type = $self->_getByFieldName('rProductType') || '';
        if ( $type =~ /Audio/i ) {
            return BookPub::DB::Item::Sale::kProductTypeAudioBook;
        }
        $self->fail("Unsupported product type '$type'.");
    }

    # MMUS only
    if ( $version == 2 && $clientID == 318 && $self->filename =~ /Macmillan[ _]\d{6}[ _]Bulk[ _]Audio/i ) {
        return BookPub::DB::Item::Sale::kProductTypeAudioBook;
    }

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

sub rFormat {
    my $self = shift;

    if ( $self->version == 2 ) {
        my $format = $self->_getByFieldName('rFormat') || '';
        if ( $format =~ /^ebook$/i ) {
            return BookPub::DB::Item::Sale::kFormatTypeEPub;
        }
    }

    return;
}

sub currencyCode {
    my $self = shift;

    my $code = $self->_getByFieldName('currencyCode') || '';
    return 'EUR' if (!$code && Common::RSApp::GetClientID == 355);

    return $code;
}

sub rTaxAmount {
    my $self = shift;

    if ( $self->_version == 2 ) {
        my $amount = $self->_getByFieldName('rTaxAmount') || 0;
        $amount =~ s/^-$//g;
        $amount =~ s/[^0-9.-]//g;
        return $amount;
    }
    if ( $self->_version == 3 ) {
        my $amount = $self->_getByFieldName('rTaxAmount') || 0;
        return $amount;
    }

    return $self->units * $self->rTaxUnitPrice;
}

sub rListPrice {
    my $self = shift;

    my $price = $self->_getByFieldName('rListPrice') || 0;
    $price =~ s/[^0-9.-]//g;

    return $price;
}

sub rPurchasePrice {
    my $self = shift;

    my $price = $self->_getByFieldName('rPurchasePrice') || 0;
    $price =~ s/[^0-9.-]//g;

    return $price;
}

sub rTaxUnitPrice {
    my $self = shift;

    my $price = $self->_getByFieldName('rTaxUnitPrice') || 0;
    $price =~ s/[^0-9.-]//g;

    return $price;
}

sub rUnitPrice {
    my $self = shift;

    if ( $self->rRevenue && $self->rUnits ) {
        return $self->rRevenue / $self->rUnits;
    }

    return 0;
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue') || 0;
    $revenue =~ s/[^0-9.-]//g;

    return $revenue;
}

sub countryCode {
    my $self = shift;

    my $code = $self->_getByFieldName('countryCode') || '';
    # CA is now also allowed; see RSD-11887 (previously restricted in RSD-5797).
    if ( $self->_version == 2 && $self->filename =~ /Bulk/i ) {
        $self->fail("Unsupported country_code '$code' for the Bulk file.") if $code !~ /^(?:CA|US|United States)/i;
    }

    return $code;
}

sub isFree {
    my $self = shift;

    return (((!$self->rRevenue || $self->rRevenue =~ /^0.0+/) && $self->rUnits) ? 'Y' : 'N');
}

1;
