package BookPub::Import::Importer::TBSDirect::Version1;

use strict;

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

sub _fieldMap {
    {
        # Detail
        rPriceType         => 'AK',
        currencyCode       => 'I',
        countryCode        => 'AL',
        dateBegin          => 'O',
        rFormat            => 'AD',
        rIsbn13            => 'U',
        rTitle             => 'X',
        rAuthor            => 'Y',
        rImprint           => 'AC',
        rUnits             => 'AH',
        rSales             => 'AF',
        rReturns           => 'AG',
        rListPrice         => 'AM',
        rListPriceCurrency => 'AO',
        rRevenue           => 'BC',
    };
}

sub _unverifiedFieldMap {
    { altCountryCode => 'N', };
}

sub _useIsSaleRec { 1 }

sub _dateFormat  { ['iso'] }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

sub _headerIdentifier { ( rTitle => 'Product title' ) }

# column N may contain the country code if it's not in AL
# it will in the format "Some Service Name:XX" where XX is the ISO code
sub countryCode {
    my $self       = shift;
    my $country    = $self->_getByFieldName('countryCode');
    my $altCountry = $self->_getByFieldName('altCountryCode');

    if ( defined($country) && length($country) > 0 ) {
        return $country;
    }

    if ( undef($country) || length($country) == 0 ) {
        if ( $altCountry =~ /\w+\:([A-Z][A-Z])/ ) {
            return $1;
        }
    }

    $self->fail("Country code not found");
}

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

    # format the date
    if ( $date =~ /(\d{4})(\d{2})(\d{2})/ ) {
        $date = $1 . "-" . $2 . "-" . $3;
    }

    return $date;
}

sub priceType {
    my $self = shift;
    my $type = lc( $self->rPriceType ) || return;

    if ( $type eq '1' ) {
        $type = 'agency';
    } elsif ( $type eq '2' ) {
        $type = 'rrp';
    }

    return $type;
}

sub rReturns {
    my $self = shift;
    my $returns = $self->SUPER::rReturns() || return;

    return $returns < 0 ? abs($returns) : 0;
}

sub rSales {
    my $self = shift;
    my $sales = $self->SUPER::rSales() || return;

    return $sales >= 0 ? $sales : 0;
}

###
1;    # Play nicely.
###
