package BookPub::Import::Importer::GooglePromotions::Version1;

use strict;

use Data::Dumper;

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

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

sub _fieldMap {
    {
        dateBegin  => 'A',
        rIsbn13    => 'D',
        rTitle     => 'C',
        rUnits     => 'B',
        rListPrice => 'E',
        rRevenue   => 'F',
    };
}

sub priceType          { 'agency' }
sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypePromotional }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub currencyCode       { 'USD' }
sub countryCode        { 'US' }
sub _dateNormalization { 'month' }

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

    if ( $date eq 'TOTAL' ) {
        $self->{_endOfData} = 1;
        return 0;
    }

    # 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 dateBegin {
    my $self = shift;
    my $startDate = $self->_getDateBegin() || return;
    my $date;

    # this is really ugly, but Google put in an odd date range and it's easier to
    # handle it thus - SB
    if ( $startDate =~ m/Sept and Oct/ ) {
        $date = new Common::Date( date => "09/01/2012", type => $self->_dateFormat() );
        return $date->monthBegin();
    }

    $date = new Common::Date( date => $startDate, type => $self->_dateFormat() );
    return $date->monthBegin();
}

sub dateEnd {
    my $self = shift;
    my $endDate = $self->_getDateBegin() || return;
    my $date;

    if ( $endDate =~ m/Sept and Oct/ ) {
        $date = new Common::Date( date => "10/15/2012", type => $self->_dateFormat() );
        return $date->asString();
    }

    my $date = new Common::Date( date => $endDate, type => $self->_dateFormat() );
    return $date->monthEnd();
}

sub _isValidSaleRecord {
    my $self = shift;

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

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

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