package BookPub::Import::Importer::Koorong::Version1;

use strict;

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

use lib '/app/tools/sale_import/lib/';
use Import::ValidationError;

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

sub _headerIdentifier { ( rIsbn13 => 'ISBN' ) }

sub _fieldMap {
    {
        # Detail
        currencyCode       => 'I',
        countryCode        => 'J',
        rIsbn13            => 'A',
        rTitle             => 'B',
        rUnits             => 'C',
        rListPrice         => 'D',
        rListPriceCurrency => 'I',
        rDiscount          => 'F',
        rRevenue           => 'H',
    };
}

sub _useIsSaleRec { 1 }

sub priceType     { 'rrp' }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType   { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _getDateBegin { shift->{_dateBegin} }
sub _getDateEnd   { shift->{_dateEnd} }

sub _preProcess {
    my $self = shift;
    my %args = @_;

    Log->info("Starting _preProcess");
    $self->SUPER::_preProcess(%args);

    foreach my $sheet ( @{ $args{sheets} } ) {
        foreach my $line (@$sheet) {

            # Since we're at the preProcess stage, it seems we have to reference rows by number.
            my $dateCell = $line->[0];
            if ( $dateCell =~ m/from (\d{2})\/(\d{2})\/(\d{4}) to (\d{2})\/(\d{2})\/(\d{4})/ ) {
                my $dateBegin = $3 . "-" . $2 . "-" . $1;
                $self->{_dateBegin} = $dateBegin;
                my $dateEnd = $6 . "-" . $5 . "-" . $4;
                $self->{_dateEnd} = $dateEnd;
                last;
            }
        }
    }
}

sub rDiscount {
    my $discount = shift->SUPER::rDiscount() || return;

    return 1 - $discount;
}

sub _isSaleRec {
    my $self = shift;

    return if ( $self->rIsbn13 =~ /TOTAL/i );
    return if ( $self->rIsbn13 =~ /End of Report/i );

    return $self->SUPER::_isSaleRec();
}

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    if ( $title =~ /^E (.*)$/ ) {
        $title = $1;
    }
    return $title;
}

1;
