package BookPub::Import::Importer::RedShelf;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        2 => {
            purchaseType => 'N',
            countryCode  => 'U',
            rState       => 'S',
            rPostalCode  => 'T',
            dateBegin    => 'A',
            rIsbn13      => 'G',
            rTitle       => 'E',
            rAuthor      => 'F',
            rListPrice   => 'I',
            rRevenue     => 'L',
            rDuration    => 'O',
        },
        3 => {
            purchaseType => 'O',
            countryCode  => 'V',
            rState       => 'T',
            rPostalCode  => 'U',
            dateBegin    => 'A',
            dateEnd      => 'A',
            rIsbn13      => 'I',
            rTitle       => 'G',
            rAuthor      => 'H',
            rImprint     => 'F',
            rFee         => 'L',
            rListPrice   => 'K',
            rTaxAmount   => 'Q',
            rRevenue     => 'M',
            rDuration    => 'P',
        },
        4 => {
            purchaseType => 'Q',
            countryCode  => 'X',
            rState       => 'V',
            rPostalCode  => 'W',
            dateBegin    => 'A',
            dateEnd      => 'A',
            rIsbn13      => 'I',
            rTitle       => 'G',
            rAuthor      => 'H',
            rImprint     => 'F',
            rListPrice   => 'K',
            rTaxAmount   => 'N',
            rDiscount    => 'L',
            rRevenue     => 'O',
            rDuration    => 'R',
        },
    );

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

sub _unverifiedFieldMap {
    my $self = shift;

    # subtotal and unusedIsbn are used in isSaleRec
    my %fieldMap = (
        2 => {
            subtotal   => 'H',
            unusedIsbn => 'H',
            status     => 'M',
        },
        3 => {
            subtotal   => 'I',
            unusedIsbn => 'J',
            status     => 'N',
        },
        4 => {
            subtotal   => 'J',
            unusedIsbn => 'J',
            status     => 'P',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub currencyCode               { 'USD' }
sub rListPriceCurrency         { 'USD' }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }

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

    return substr( $dateBegin, 0, 10 );
}

sub priceType {
    my $self = shift;

    my $type;
    my $clientID = Common::RSApp::GetClientID;

    if ( $clientID == 318 ) {    # Macmillan is always agency
        $type = 'agency';
    } else {
        $type = 'rrp';
    }

    return $type;
}

sub rSales {
    my $self = shift;

    my $status = $self->_getByFieldName('status');
    if ( uc($status) eq 'ACTIVE' ) {
        return 1;
    } elsif ( uc($status) eq 'REFUNDED' ) {
        return 0;
    }
    $self->fail("Unknown status: $status");
}

sub rReturns {
    my $self = shift;

    my $status = $self->_getByFieldName('status');
    if ( uc($status) eq 'ACTIVE' ) {
        return 0;
    } elsif ( uc($status) eq 'REFUNDED' ) {
        return 1;
    }
    $self->fail("Unknown status: $status");
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue');
    my $status  = $self->_getByFieldName('status');
    $revenue = abs($revenue);
    if ( uc($status) eq 'ACTIVE' ) {
        return $revenue;
    } elsif ( uc($status) eq 'REFUNDED' ) {
        $revenue *= -1;
        return $revenue;
    }
    $self->fail("Unknown status: $status");
}

sub rTaxAmount {
    my $self = shift;

    my $tax = $self->_getByFieldName('rTaxAmount') || return;

    if ( uc($tax) ne 'EXEMPT' ) {
        my $status = $self->_getByFieldName('status');
        $tax = abs($tax);
        if ( uc($status) eq 'ACTIVE' ) {
            return $tax;
        } elsif ( uc($status) eq 'REFUNDED' ) {
            $tax *= -1;
            return $tax;
        }
        $self->fail("Unknown status: $status");
    }
}

sub rAuthor {
    my $self = shift;

    my $author = $self->_getByFieldName('rAuthor');
    if ( $author ne "-" && $author ne "0" ) {
        return $author;
    }

}

sub purchaseType {
    my $self = shift;

    my $type = $self->_getByFieldName('purchaseType');
    if ( lc($type) eq 'digital' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeDownload;
    }
    if ( lc($type) eq 'lifetime' || lc($type) eq 'limited' ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }
    if ( $type =~ /^\d+$/ ) {
        return BookPub::DB::Item::Sale::kPurchaseTypeLoan;
    }
    $self->fail("Unknown purchase type: $type");

}

sub rDiscount {
    my $self = shift;

    my $discount  = $self->_getByFieldName('rDiscount') || 0;
    my $listPrice = $self->rListPrice;

    $discount = $self->_correctFormat($discount);

    if ( $discount && $listPrice ) {
        $discount /= $listPrice;
        return $discount;
    }

    return;
}

sub _correctFormat {
    my ($self, $amount) = @_;

    return 0 unless $amount;

    my $sign = $amount =~ /^[-(]/ ? -1 : 1;
    $amount =~ s/^\(|\)$//g;
    $amount =~ s/^[^0-9]//;
    $amount *= $sign;

    return $amount;
}

sub _isSaleRec {
    my $self = shift;

    # We're going to check for the subtotal line
    my $subtotal   = $self->_getByFieldName('subtotal');
    my $unusedIsbn = $self->_getByFieldName('unusedIsbn');
    if ( $subtotal =~ /^TOTALS?$/i || $unusedIsbn =~ /^TOTALS?$/i ) {
        return 0;
    }

    # Also need to ignore the second set of headers
    my $date = $self->_getByFieldName('dateBegin');
    if ( uc($date) eq 'REFUNDED' || uc($date) eq 'DATE' ) {
        return 0;
    }

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

1;
