package BookPub::Import::Importer::OpenRoadMedia::v4;

use strict;
use warnings;

use Date::Calc qw(Days_in_Month);

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

sub _fieldMap {
    {
        rAuthor    => 'C',
        rTitle     => 'B',
        rIsbn13    => 'A',
        rUnits     => 'F',
        rRevenue   => 'J',
        rComments  => 'E',
    };
}

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 _headerIdentifier { rTitle => 'Title' }

sub priceType          { 'rrp' }
sub countryCode        { 'US' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub rPurchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }

sub rServiceName { 'Open Road Media' }

sub dateBegin {
    my $self = shift;

    my ($m, $y) = $self->filename =~ /(\w{3,9})[_ \.](\w{4})/i;
    $m = lc(substr($m, 0, 3));
    if ( $y && $m && exists $months{ $m } ) {
        return sprintf "%04d-%02d-%02d", $y, $months{ $m }, 1;
    }

    $self->fail("Unable to determine date_begin from the filename.");
}

sub dateEnd {
    my $self = shift;

    my ($m, $y) = $self->filename =~ /(\w{3,9})[_ \.](\w{4})/i;
    $m = lc(substr($m, 0, 3));
    if ( $y && $m && exists $months{ $m } ) {
        return sprintf "%04d-%02d-%02d", $y, $months{ $m }, Days_in_Month( $y, $months{ $m } );
    }

    $self->fail("Unable to determine date_end from the filename.");
}

sub rUnits {
    my $self = shift;

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

    $rUnits *= -1 if $rRevenue < 0 && $rUnits > 0;

    return $rRevenue <=> 0 unless $rUnits;

    return $rUnits;
}

sub rUnitPrice {
    my $self = shift;

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

    return $rUnits ? $rRevenue / $rUnits : 0;

}

sub rListPrice { shift->rUnitPrice }

sub isFree {
    my $self = shift;

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

sub _isValidSaleRecord {
    my $self = shift;

    # MMUS
    if ( Common::RSApp::GetClientID() != 318 ) {
        $self->fail("Cannot parse the file for this client.");
    }

    return 0 if !$self->rRevenue && !$self->rUnits;

    return 1;
}


1;
