package BookPub::Import::Importer::Faithlife::v1;

use strict;
use Data::Dumper;

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

sub _headerIdentifier { ( rTitle => 'Rightholder Resource Name' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            rTitle         => 'A',
            rIsbn13        => 'B',
            rUnits         => 'E',
            rListPrice     => 'C',
            rPurchasePrice => 'D',
            rRevenue       => 'F',
        },
    );

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

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

sub purchaseType           { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType            { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType              { 'rrp' }
sub currencyCode           { 'USD' }
sub countryCode            { 'US' }
sub rListPriceCurrency     { 'USD' }
sub rPurchasePriceCurrency { 'USD' }

sub _dateFormat                { ['iso'] }
sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }

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

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

    $self->SUPER::_preProcess(%args);

    my $sheetnum = 0;
    foreach my $sheet ( @{ $args{sheets} } ) {
        my $sheetname = $args{sheet_names}->[$sheetnum];
        $sheetnum++;

        Common::Log::Print("sheetname: $sheetname");
        if ( $sheetname =~ /(\w{3,9}) (\d{4})/i ) {
            $self->{_dateBegin} = $2 . '-' . $monthNames{ lc($1) } . "-01";
        }
        last;
    }
}

sub _getDateBegin { shift->{_dateBegin} }

sub _processLine {
    my $self = shift;

    if ( $self->rTitle() =~ /Grand Total/i ) {
        $self->{_endOfData} = 1;
        return;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

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

1;
