package BookPub::Import::Importer::CampusEbookstore::v1;

use strict;
use warnings;


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

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


sub _fieldMap {
    {
        dateBegin          => 'A',
        dateEnd            => 'A',
        rTitle             => 'F',
        rIsbn13            => 'M',
        rInstitution       => 'D',
        serviceProductID   => 'E',
        rUnits             => 'G',
        rUnitPrice         => 'J',
        rListPrice         => 'H',
        rListPriceCurrency => 'L',
        rDiscount          => 'I',
        rRevenue           => 'K',
        currencyCode       => 'L',
    };
}

sub _headerIdentifier { rIsbn13 => 'ISBN' }

sub _useIsSaleRec { 1 }
sub rServiceName  { 'Campus eBookstore' }
sub priceType     { 'rrp' }
sub countryCode   { 'US' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }

sub dateBegin {
    my $self = shift;

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

    return $date if ( $date =~ /^\d{4}-\d{2}-\d{2}$/ );

    # YYYY-MM
    if ( $date =~ /^(\d{4})-(\d{1,2})$/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, 1;
    }
    # DD.MM.YYYY
    if ( $date =~ /^(\d{2}).(\d{2}).(\d{4})/ ) {
        return sprintf "%04d-%02d-%02d", $3, $2, $1;
    }

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

sub dateEnd {
    my $self = shift;

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

    return $date if ( $date =~ /^\d{4}-\d{2}-\d{2}$/ );

    # YYYY-MM
    if ( $date =~ /^(\d{4})-(\d{1,2})$/ ) {
        return sprintf "%04d-%02d-%02d", $1, $2, Days_in_Month( $1, $2 );
    }
    # DD.MM.YYYY
    if ( $date =~ /^(\d{2}).(\d{2}).(\d{4})/ ) {
        return sprintf "%04d-%02d-%02d", $3, $2, Days_in_Month($3, $2);
    }

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

sub rTitle {
    my $self = shift;

    my $title = $self->_getByFieldName('rTitle') || "";
    $title =~ s/^.+?: ?//;

    return $title;
}

sub serviceProductID {
    my $self = shift;

    my $id = $self->_getByFieldName('serviceProductID') || "";
    $id =~ s/^\[|\]$//g;

    return $id;
}

sub isFree {
    my $self = shift;

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

1;
