package BookPub::Import::Importer::Libri::Version3;

use strict;

use lib '/app/tools/common/lib';
use Common::Date;
use Common::Log;

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 = (
        3 => {
            dateBegin                => 'T',
            rProductType             => 'N',
            rFormat                  => 'N',
            rPriceType               => 'U',
            priceTypeQualifierID     => 'V',
            rAuthor                  => 'M',
            rTitle                   => 'L',
            rIsbn13                  => 'J',
            countryCode              => 'S',
            rClientProductID         => 'K',
            serviceProductID         => 'I',
            rUnits                   => 'O',
            rUnitPrice               => 'W',
            rListPrice               => 'AI',
            rListPriceCurrency       => 'AJ',
            rDiscount                => 'AB',
            rRevenue                 => 'AC',
            currencyCode             => 'AD',
            rTaxAmount               => 'AM',
        },
        4 => {
            dateBegin                => 'T',
            rProductType             => 'N',
            rFormat                  => 'N',
            rPriceType               => 'U',
            priceTypeQualifierID     => 'V',
            rAuthor                  => 'M',
            rTitle                   => 'L',
            rIsbn13                  => 'J',
            countryCode              => 'S',
            rClientProductID         => 'K',
            serviceProductID         => 'I',
            rReturns                 => 'AO',
            rSales                   => 'O',
            rUnits                   => 'O',
            rUnitPrice               => 'W',
            rListPrice               => 'AI',
            rListPriceCurrency       => 'AJ',
            rDiscount                => 'AB',
            rRevenue                 => 'AC',
            currencyCode             => 'AD',
            rTaxAmount               => 'AM',
        },
        5 => {
            dateBegin                => 'U',
            dateEnd                  => 'U',
            rProductType             => 'N',
            rFormat                  => 'N',
            rPriceType               => 'V',
            priceTypeQualifierID     => 'W',
            rAuthor                  => 'M',
            rTitle                   => 'L',
            rIsbn13                  => 'J',
            countryCode              => 'T',
            rClientProductID         => 'K',
            serviceProductID         => 'I',
            rReturns                 => 'AR',
            rUnits                   => 'O',
            rListPrice               => 'X',
            rListPriceCurrency       => 'Y',
            rPurchasePrice           => 'AL',
            rPurchasePriceCurrency   => 'AM',
            rDiscount                => 'AD',
            rRevenue                 => 'AF',
            currencyCode             => 'AG',
            rTaxAmount               => 'AP',
            rChannel                 => 'AQ',
            rTransactionCategory     => 'S',
        },
    );

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

sub countryCode {
    my $self = shift;

    my $countryCode = $self->_getByFieldName('countryCode');

    return $countryCode || $self->fail("Can't determine country_code from '$countryCode'.");

}

sub _headerIdentifier { ( rTitle => 'Title' ) }
sub _useIsSaleRec     { 1 }
sub _dateFormat       { ['numerical_year_first'] }
sub purchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub rServiceName {
    return BookPub::Tracker::Service::GetDefaultServiceName( service_id => shift->serviceID );
}

sub priceTypeQualifierID {
    my $self = shift;
    my $id   = $self->_getByFieldName('priceTypeQualifierID');

    if (   $id =~ /UnitCostExcludingTax/i
        || $id =~ /SoldAtPriceExcludingTax/i ) {
        return BookPub::DB::Item::PriceTypeQualifier::kUnqualified;
    }

    $self->fail("Unexpected price type qualifier id $id");
}

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

    if ( $format eq 'epb' ) {
        return BookPub::DB::Item::Sale::kFormatTypeEPub;
    } elsif ( $format eq 'pdf' && $self->_version =~ /^(?:4|5)$/ ) {
        return BookPub::DB::Item::Sale::kFormatTypePDF;
    }

    $self->fail("Unexpected format: $format");
}

sub productType {
    my $self = shift;
    my $type = lc( $self->_getByFieldName('rProductType') || '' );

    if ( $type eq 'epb' ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    } elsif ( $type eq 'pdf' && $self->_version =~ /^(?:4|5)$/ ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Unknown product type: $type");
}

sub priceType {
    my $self = shift;
    my $type = $self->_getByFieldName('rPriceType');

    if ( lc($type) eq 'wholesale' ) {
        return 'rrp';
    } elsif ( lc($type) eq 'agency' ) {
        return 'agency';
    }

    $self->fail("Unknown price type: $type");
}

sub rTitle {
    my $self  = shift;
    my $title = $self->_getByFieldName('rTitle');

    $title =~ s/^'// if ($title);
    $title =~ s/'$// if ($title);

    return $title;
}

sub rAuthor {
    my $self   = shift;
    my $author = $self->_getByFieldName('rAuthor');

    $author =~ s/^'// if ($author);
    $author =~ s/'$// if ($author);

    return $author;
}

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

    if ( $dateBegin =~ /(\d{2})\/(\d{2})\/(\d{4})/ ) {
        $dateBegin = $3 . "-" . $2 . "-" . $1;
    }

    return $dateBegin;
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');

    # We need to make this negative if it's a return.
    if ( defined $self->_getByFieldName('rReturns') && $self->_getByFieldName('rReturns') ) {
        $revenue = abs($revenue) * -1;
    }

    return $revenue;
}

sub rTaxAmount {
    my $self = shift;
    my $tax  = $self->_getByFieldName('rTaxAmount');

    # We need to make this negative if it's a return.
    if ( defined $self->_getByFieldName('rReturns') && $self->_getByFieldName('rReturns') ) {
        $tax = abs($tax) * -1;
    }

    return $tax;
}

sub rUnits {
    my $self = shift;

    my $rUnits    = $self->_getByFieldName('rUnits')   || 0;
    my $rReturns  = $self->_getByFieldName('rReturns') || 0;

    if ( $rUnits && $rReturns ) {
        $rUnits = abs($rUnits) * -1 if $self->_version =~ /^(?:4|5)$/;
    } elsif ( !$rUnits && $rReturns ) {
        $rUnits = abs( $rReturns || 0 ) * -1 if $self->_version =~ /^(?:4|5)$/;
    }

    return $rUnits;
}

sub isFree {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue') || 0;
    my $units = $self->_getByFieldName('rUnits') || 0;
    my $returns = $self->_getByFieldName('rReturns') || 0;

    return "Y" if ($revenue == 0 && ($units > 0 || $returns < 0));
    return "N";
}

1;
