package BookPub::Import::Importer::TheBookPeople::Version1;

use strict;

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

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

sub _fieldMap {
    {
        currencyCode       => 'H',
        countryCode        => 'F',
        dateBegin          => 'L',
        rFormat            => 'D',
        isbn               => 'A',
        rTitle             => 'B',
        rImprint           => 'C',
        rSales             => 'N',
        rReturns           => 'O',
        rListPrice         => 'K',
        rListPriceCurrency => 'K',
        rRevenue           => 'P',
    };
}

##########################################
# !!!!!!!!!!!!!!!!!!!!!!!!
# Deprecating this version
# !!!!!!!!!!!!!!!!!!!!!!!!
#########################################

sub _importLines {
    my $self = shift;

    $self->fail("This file matches Version 1 of this importer, which has been deprecated.");
}

sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }
sub priceType    { 'rrp' }
sub _dateFormat  { [ 'numerical_year_first', 'iso' ] }

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

    if ( lc($code) eq 'pounds sterling' ) {
        return 'GBP';
    } else {
        return $code;
    }
}

sub rListPriceCurrency { return shift->currencyCode() }

sub _getDateBegin {
    my $self = shift;
    my $date = $self->_getByFieldName('dateBegin') || return;

    # strip off the time stamp
    if ( $date =~ /^(\d{4}-\d{2}-\d{2})/ ) {
        return $1;
    }

    # the date is being returned in the "days since 1/1/1900" format, so we need
    # to convert it.  We'll check if it's a 5 digit number and greater than the
    # number of days since 1/1/1900 on 1/1/2006, which is 38716
    if ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
        return $date;
    }

    return $date;
}

sub _validTabNames { ['Latest Sales'] }

sub _isValidSaleRecord {
    my $self = shift;

    # Only process sales from the transaction sheets
    my $validTab;
    my $validTabNames = _validTabNames();
    foreach my $validTabName (@$validTabNames) {
        if ( $self->sheetname() =~ /$validTabName/i ) {
            $validTab = 1;
        }
    }
    return undef unless $validTab;

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

###
1;    # Play nicely.
###
