package BookPub::Import::Importer::Waterstones::Version1;

use strict;

use Common::Country;
use Common::Date;

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

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

sub _fieldMap {
    {
        # Header
        dateEnd => 'E',

        # Data rows
        isbn       => 'F',
        rTitle     => 'G',
        rUnits     => 'B',
        rSales     => 'L',
        rReturns   => 'L',
        rListPrice => 'N',
        rRevenue   => 'M',
    };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub currencyCode { 'GBP' }
sub countryCode  { 'GB' }

sub _processHeader { shift->_storeDate() }

sub revenue {
    my $self = shift;
    return $self->units >= 0 ? $self->rRevenue() : $self->rRevenue * -1;
}

sub _storeDate {
    my $self = shift;

    return if ( $self->_getDateEnd() );

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

    $self->{_dateEnd} = $date if ( $date && $date =~ /\d+\/\d+\/\d+/ );
}

sub _getDateEnd { shift->{_dateEnd} }

sub _dateFormat { 'eur' }

sub dateBegin {
    my $self    = shift;
    my $dateEnd = $self->dateEnd();

    my $date = Common::Date->new($dateEnd);

    $date->addDays(-7);

    return $date->asString;
}

sub rTitle {
    my $self  = shift;
    my $title = $self->_getByFieldName('rTitle');

    $title =~ s/\s\(eBook\)$// if ($title);
    $title =~ s/\s\(eBook$//   if ($title);
    $title =~ s/\s\(eBoo$//    if ($title);
    $title =~ s/\s\(eBo$//     if ($title);
    $title =~ s/\s\(eB$//      if ($title);
    $title =~ s/\s\(e$//       if ($title);
    $title =~ s/\s\($//        if ($title);
    $title =~ s/\s$//          if ($title);

    return $title;
}

sub rUnits { undef }

sub rSales {
    my $self  = shift;
    my $type  = $self->_getByFieldName('rUnits');
    my $sales = $self->_getByFieldName('rSales');

    return unless ($type);
    die "Unknown sale type '$type'" unless ( $type =~ /^(i|c)$/i );

    return lc($type) eq 'i' ? $sales : 0;
}

sub rReturns {
    my $self    = shift;
    my $type    = $self->_getByFieldName('rUnits');
    my $returns = $self->_getByFieldName('rReturns');

    return unless ($type);
    die "Unknown sale type '$type'" unless ( $type =~ /^(i|c)$/i );

    return lc($type) eq 'c' ? $returns : 0;
}

sub listPrice {
    abs( shift->SUPER::rListPrice() );
}

1;
