package BookPub::Import::Importer::Libro::v1;

use strict;
use warnings;

use lib '/app/tools/bookpub/lib';
use Date::Calc qw(Days_in_Month);

use parent 'BookPub::Import::Importer';

sub _fieldMap {
    my $self = shift;

    my %map = (
        1 => {
            rServiceName  => 'A1',
            rPurchaseType => 'F',
            purchaseType  => 'F',
            rAuthor       => 'C',
            rTitle        => 'B',
            rIsbn13       => 'D',
            countryCode   => 'K',
            rUnits        => 'I',
            rUnitPrice    => 'H',
            rListPrice    => 'E',
            rDiscount     => 'G',
            rRevenue      => 'J',
        },
        2 => {
            rServiceName       => 'A1',
            rPurchaseType      => 'G',
            purchaseType       => 'G',
            rAuthor            => 'C',
            rTitle             => 'B',
            rIsbn13            => 'D',
            countryCode        => 'M',
            rUnits             => 'K',
            rUnitPrice         => 'I',
            rListPrice         => 'E',
            rListPriceCurrency => 'F',
            rDiscount          => 'H',
            rRevenue           => 'N',
            currencyCode       => 'N',
        },
    );

    return $map{ $self->version };
}

sub _unverifiedFieldMap { }
sub _headerIdentifier { rAuthor => 'Author' }

my %months = (
    jan => 1,
    feb => 2,
    mar => 3,
    apr => 4,
    may => 5,
    jun => 6,
    jul => 7,
    aug => 8,
    sep => 9,
    oct => 10,
    nov => 11,
    dec => 12,
);

sub _useIsSaleRec      { 1 }
sub rPurchaseType      { $_[0]->purchaseType }
sub productType        { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub rProductType       { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub priceType          { 'rrp' }

sub _processHeader {
    my $self = shift;

    if (!$self->{_currencyCode}) {
        my $currency = $self->_getByFieldName('currencyCode') || '';
        $self->{_currency_code} = $1 if ($currency =~ /^Total in (\w{3})$/);
    }

    return $self->SUPER::_processHeader(@_);
}


sub rServiceName { 'Libro.fm' }

sub rListPriceCurrency {
    my $self = shift;

    return 'USD' if $self->version == 1;

    my $currency = $self->_getByFieldName('rListPriceCurrency') || '';
    return $currency;
}

sub currencyCode {
    my $self = shift;

    return 'USD' if $self->version == 1;

    return $self->{_currency_code} if $self->{_currency_code};

    $self->fail("Can't determine currency");
}

sub dateBegin {
    my $self = shift;

    my $fileName = $self->filename();
    if ( $fileName =~ /([a-z]{3})(?:[a-z]{1,6})?[ _-](\d{4})\..+/i ) {
        return sprintf "%04d-%02d-%02d", $2, $months{ lc $1 }, 1;
    }
    elsif ( $fileName =~ /^(\d{4})-(\d{2})/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, 1;
    }

    $self->fail("Can't determine dateBegin from: '$fileName'.");
}

sub dateEnd {
    my $self = shift;

    my $fileName = $self->filename();
    if ( $fileName =~ /([a-z]{3})(?:[a-z]{1,6})?[ _-](\d{4})\..+/i ) {
        return sprintf "%04d-%02d-%02d", $2, $months{ lc $1 }, Days_in_Month( $2, $months{ lc $1 } );
    }
    elsif ( $fileName =~ /^(\d{4})-(\d{2})/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, Days_in_Month( $1, $2 );
    }

    $self->fail("Can't determine dateEnd from: '$fileName'.");
}

sub purchaseType {
    my $self = shift;

    my $type = $self->_getByFieldName('purchaseType') || '';
    return BookPub::DB::Item::Sale::kPurchaseTypeDownload       if $type =~ /^(?:A la Carte|BOGO)$/i;
    return BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL if $type =~ /^Subscription$/i;

    $self->fail("Unable to determine purchase_type from: '$type'.");
}

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

    return ($revenue < 0) ? (abs($units) * -1) : $units;
}

sub isFree {
    my $self = shift;

    return if $self->version == 1;

    return !$self->rRevenue && $self->rUnits ? 'Y' : 'N';
}

sub _isSaleRec {
    my $self = shift;

    my $rUnits       = $self->_getByFieldName('rUnits');
    my $rRevenue     = $self->_getByFieldName('rRevenue');
    my $isbn         = $self->_getByFieldName('rIsbn13');
    my $title        = $self->_getByFieldName('rTitle');
    my $author       = $self->_getByFieldName('rAuthor');
    my $purchaseType = $self->_getByFieldName('purchaseType');

    if ( !$rUnits && !$rRevenue && !$isbn && !$title && !$author ) {
        return 0;
    } elsif ( !$purchaseType || $purchaseType =~ /^Purchase type$/i ) {
        return 0;
    }

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


1;
