package BookPub::Import::Importer::Bloomsbury::v1;

use strict;
use Data::Dumper;

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

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

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

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rFormat     => 'I',
            rTitle      => 'H',
            rIsbn13     => 'J',
            countryCode => 'E',
            rUnits      => 'L',
            rUnitPrice  => 'N',
            rRevenue    => 'M',
        },
    );

    return $fieldMap{ $self->_version() };
}

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeLoan }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType    { 'rrp' }

sub _useIsSaleRec      { 1 }
sub _dateFormat        { ['iso'] }
sub _dateNormalization { 'month' }

sub dateBegin {
    my $self = shift;
    my $year;
    my $month;
    my %monthNames = (
        "january"   => "01",
        "jan"       => "01",
        "february"  => "02",
        "feb"       => "02",
        "march"     => "03",
        "mar"       => "03",
        "april"     => "04",
        "apr"       => "04",
        "may"       => "05",
        "june"      => "06",
        "jun"       => "06",
        "july"      => "07",
        "jul"       => "07",
        "august"    => "08",
        "aug"       => "08",
        "september" => "09",
        "sep"       => "09",
        "october"   => "10",
        "oct"       => "10",
        "november"  => "11",
        "nov"       => "11",
        "december"  => "12",
        "dec"       => "12",
    );

    # if date is missing, use the date from the filename
    if ( $self->filename =~ / (\w{3,9}) (\d{4})/ ) {
        $year = $2;
        my $monthName = lc($1);
        if ( $monthNames{$monthName} ) {
            $month = $monthNames{$monthName};
        } else {
            $self->fail("Bad month value in filename, $self->filename");
        }
    } else {
        $self->fail("Couldn't find date in filename, $self->filename");
    }
    my $date = sprintf( "%04d-%02d-%02d", $year, $month, 1 );
    return $date;
}

sub countryCode {
    my $self = shift;
    my $code;

    if ( $self->filename =~ / (\w{2}) Ebook/ ) {
        $code = $1;
    } else {
        $self->fail("Couldn't find country code in filename, $self->filename");
    }
    return $code;
}

sub currencyCode {
    my $self        = shift;
    my $countryCode = $self->countryCode();
    my $code;

    if ($countryCode) {
        my $currencyObj = Common::CurrencyFormat->new( countryCode => $countryCode );
        $code = $currencyObj->currencyCode();
    } else {
        $self->fail("Couldn't find currency code from country: $countryCode");
    }
    return $code;
}

1;
