package BookPub::Import::Importer::Casalini::v1;

use strict;
use warnings;

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

use base 'BookPub::Import::Importer';


sub _fieldMap {
    my $self = shift;

    my %map = (
        'institutional sales' => {    # Institutional Sales
            rPurchaseType        => 'L',
            rTitle               => 'D',
            rIsbn13              => 'C',
            countryCode          => 'G',
            rUnits               => 'E',
            rListPrice           => 'I',
            discount             => 'J',
            rRevenue             => 'M',
            rTransactionCategory => 'L',
        },
        'individual sales' => {    # Individual Sales
            rPurchaseType        => 'H',
            rTitle               => 'D',
            rIsbn13              => 'C',
            countryCode          => 'G',
            rUnits               => 'E',
            rListPrice           => 'F',
            rRevenue             => 'I',
            rTransactionCategory => 'H',
        }
    );

    return $map{ lc $self->{sheetname} };
}


sub _headerIdentifier { rTitle => 'Title' }

sub rServiceName       { 'Casalini' }
sub priceType          { 'rrp' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _useIsSaleRec      { 1 }


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 dateBegin {
    my $self = shift;

    # [Publisher]_YYYY_#_MMM-MMM_Income_Report_Sales
    if ( $self->filename =~ /.*(\d{4}).*([a-z]{3})-([a-z]{3}).*/i ) {
        my $year = $1;
        my $month = lc $2;
        return (sprintf "%04d-%02d-%02d", $year, $months{$month}, 1);
    }

    $self->fail("Unable to determine date begin.");
}

sub dateEnd {
    my $self = shift;

    # [Publisher]_YYYY_#_MMM-MMM_Income_Report_Sales
    if ( $self->filename =~ /.*(\d{4}).*([a-z]{3})-([a-z]{3}).*/i ) {
        my $year = $1;
        my $month = lc $3;
        return (sprintf "%04d-%02d-%02d", $year, $months{$month}, Days_in_Month( $year, $months{$month} ));
    }

    $self->fail("Unable to determine date end.");
}

sub rUnitPrice {
    my $self = shift;

    if ( $self->rUnits ) {
        return $self->rRevenue / $self->rUnits;
    }

    return 0;
}

sub discount {
    my $self = shift;

    if ( $self->sheetname =~ /^Institutional Sales$/i ) {
        return $self->_getByFieldName('discount') || 0;
    }

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

sub isFree {
    my $self = shift;

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

1;
