package BookPub::Import::Importer::Mofibo::v1;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Country;

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

sub _fieldMap {
    {
        dateBegin    => 'G',
        dateEnd      => 'G',
        rProductType => 'F',
        rAuthor      => 'E',
        rTitle       => 'D',
        rIsbn13      => 'C',
        countryCode  => 'H',
        rSales       => 'L',
        rUnitPrice   => 'J',
        rListPrice   => 'L',
        rRevenue     => 'L',
    };
}

sub _headerIdentifier { ( rTitle => 'Title' ) }

sub _useIsSaleRec      { 1 }
sub priceType          { 'rrp' }
sub currencyCode       { 'GBP' }
sub rListPriceCurrency { 'GBP' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeSubscriptionDL }
sub productType        { shift->rProductType }
sub _dateFormat        { [ 'numerical', 'quarter', 'iso' ] }
sub rServiceName { BookPub::Tracker::Service::MOFIBO }

sub rProductType  {
    my $self = shift;

    my $type = $self->_getByFieldName('rProductType') || '';
    return BookPub::DB::Item::Sale::kProductTypeAudioBook if $type =~ /^AudioBook$/i;
    return BookPub::DB::Item::Sale::kProductTypeEBook     if $type =~ /^EBook$/i;

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

sub _getDateBegin {
    my $self = shift;
    $self->{_dateBegin} || $self->_setDates;
    return $self->{_dateBegin};
}

sub _getDateEnd {
    my $self = shift;
    $self->{_dateEnd} || $self->_setDates;
    return $self->{_dateEnd};
}

sub _setDates {
    my $self = shift;
    my ( $begin, $end );
    my $startDate = $self->_getByFieldName('dateBegin');

    if ( $startDate =~ /(\d)\. quarter (\d{4})/ ) {
        ( $begin, $end ) = $self->_getDates( date_begin => $2 . "Q$1", type => 'quarter' );
    } else {
        $self->fail("Cannot get date from header: $startDate");
    }

    $self->{_dateBegin} = $begin;
    $self->{_dateEnd}   = $end;
}

sub rUnits {
    my $self = shift;

    my $revenue = $self->_getByFieldName('rRevenue') || 0;

    my $units = $revenue <=> 0;
    return $units;
}

sub rSales { abs( shift->_getByFieldName('rSales') || 0 ) }

sub _isSaleRec {
    my $self = shift;

    my $title   = $self->_getByFieldName('rTitle');
    my $isbn    = $self->_getByFieldName('rIsbn13');
    my $revenue = $self->_getByFieldName('rRevenue');

    return unless $title && $isbn && $revenue;
    return $self->SUPER::_isSaleRec();
}

1;
