package BookPub::Import::Importer::SmartEbook::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 { ( dateBegin => 'Date' ) }

sub _fieldMap {
    {
        # Detail
        countryCode => 'C',
        dateBegin   => 'A',
        isbn        => 'D',
        rTitle      => 'E',
        rAuthor     => 'F',
        rUnits      => 'H',
        rListPrice  => 'G',
        rDiscount   => 'L',
        rRevenue    => 'M',
    };
}

sub priceType          { 'rrp' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub currencyCode       { shift->{_currencyCode} }
sub rListPriceCurrency { shift->{_currencyCode} }

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

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

    my $currencyCode;

    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 $currencyCodeCell = $line->[11];
            if ( $currencyCodeCell =~ m/Royalty.+(\w{3})/ ) {
                $currencyCode = $1;
                $self->{_currencyCode} = $currencyCode;
                last;
            }
        }
    }
}

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

    return 1 - $discount;
}

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;
    if ( $date && $date =~ /(\w{3}) (\d{1,2}) (\d{4})/ ) {
        my $monthName = $1;
        my $day       = $2;
        my $year      = $3;

        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,
        );

        my $month = $months{ lc($monthName) };
        $date = sprintf( "%04d-%02d-%02d", $year, $month, $day );
    }
    return $date;
}

1;
