package BookPub::Import::Importer::Yoto::v4;

use strict;
use warnings;

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

use Date::Calc qw(Days_in_Month);

sub _fieldMap {
    {
        dateBegin              => 'B5',
        rTitle                 => 'B',
        rClientProductID       => 'A',
        rUnits                 => 'C',
        rUnitPrice             => 'D',
        rListPrice             => 'D',
        rListPriceCurrency     => 'E',
        rDiscount              => 'F',
        rRevenue               => 'G',
        currencyCode           => 'E',
    };
}

sub _headerIdentifier { rTitle => 'Title' }

sub rServiceName  { 'Yoto' }
sub _useIsSaleRec { 1 }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType   { BookPub::DB::Item::Sale::kProductTypeAudioBook }
sub rPurchaseType { $_[0]->purchaseType() }
sub rProductType  { $_[0]->productType() }
sub rPriceType    { 'rrp' }
sub countryCode   { 'US' }

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';

    if ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        return Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
    }

    $self->fail("Unbale to determine date begin from '$date'.");
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->_getByFieldName("rRevenue") || 0;
    $revenue =~ s/^[^0-9]*//g;
    $revenue =~ s/,/./g;

    return $revenue;
}

sub isFree {
    my $self = shift;

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

sub _isSaleRec {
    my $self = shift;


    return if !$self->rRevenue && !$self->rTitle;

    if ( $self->rListPrice =~ /ROYALTY EARNED IN PERIOD/i || $self->{_stop_parsing} ) {
        $self->{_stop_parsing} = 1;
        return;
    }

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

1;
