package BookPub::Import::Importer::Kno::Version2;

use strict;

use Data::Dumper;

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

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

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

sub _fieldMap {
    {
        purchaseType       => 'C',
        currencyCode       => 'L',
        countryCode        => 'K',
        rState             => 'Q',
        rPostalCode        => 'R',
        isbn               => 'A',
        rTitle             => 'N',
        rAuthor            => 'M',
        rImprint           => 'O',
        rUnits             => 'G',
        rSales             => 'D',
        rReturns           => 'F',
        rListPrice         => 'H',
        rListPriceCurrency => 'L',
        rDiscount          => 'I',
        rRevenue           => 'J',
    };
}

sub _unverifiedFieldMap {
    { rRented => 'E', };
}

sub _dateNormalization { 'month' }

sub priceType   { 'agency' }
sub productType { BookPub::DB::Item::Sale::kProductTypeEBook }

sub rListPrice {
    my $self = shift;

    my $price = $self->SUPER::rListPrice();
    $price =~ s/,|\$|\(|\)//g;

    return $price;
}

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

    if ( lc($purchaseType) eq 'buy' )  { return BookPub::DB::Item::Sale::kPurchaseTypeDownload }
    if ( lc($purchaseType) eq 'rent' ) { return BookPub::DB::Item::Sale::kPurchaseTypeLoan }

    $self->fail("License Type ($purchaseType) not supported");
}

sub rRevenue {
    my $self = shift;

    my $revenue = $self->SUPER::rRevenue();
    $revenue =~ s/,|\$|\s//g;

    if ( $revenue =~ s/[\(\)]//g ) {
        $revenue *= -1;
    }

    return $revenue;
}

# sales are from two columns, sold and rented
sub rSales {
    my $self = shift;

    my $qtySold   = $self->_getByFieldName('rSales');
    my $qtyRented = $self->_getByFieldName('rRented');

    if ( $qtySold == 0 ) {
        return $qtyRented;
    } else {
        return $qtySold;
    }
}

# returns are negative values in file
sub rReturns {
    my $self = shift;
    my $returns = $self->SUPER::rReturns() || return;

    return $returns < 0 ? abs($returns) : $returns;
}

# we need to get the date from a non-consistent column in the second row.
# I'll get that line and grab the first date-looking item in it, Month 'YY
sub _preProcess {
    my $self   = shift;
    my %args   = @_;
    my %months = (
        january   => 1,
        february  => 2,
        march     => 3,
        april     => 4,
        may       => 5,
        june      => 6,
        july      => 7,
        august    => 8,
        september => 9,
        october   => 10,
        november  => 11,
        december  => 12,
    );

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

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        $sheetnum++;
        my $linenum     = 0;
        my $foundHeader = 0;
        foreach my $line (@$sheet) {
            $linenum++;
            if ( $line->[0] eq 'Contract' ) {
                $foundHeader = 1;
                foreach my $element (@$line) {
                    my $date = $element;
                    if ( $date =~ /^(\w*) \'(\d{2,4})$/ ) {
                        my $monthName = $1;
                        my $day       = 1;
                        my $year      = $2;
                        if ( length($year) == 2 ) {
                            $year = "20" + $year;
                        }
                        my $month = $months{ lc($monthName) };
                        $self->{_dateBegin} = sprintf( "%04d-%02d-%02d", $year, $month, $day );
                        return;
                    }
                }
                next;
            } elsif ( $foundHeader == 0 ) {
                next;
            }
        }
    }
}

sub _getDateBegin { shift->{_dateBegin} }

1;
