package BookPub::Import::Importer::ReadCloud;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( rIsbn13 => 'EAN' ) }

sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        1 => {
            currencyCode => 'E',
            countryCode  => 'H',
            dateBegin    => 'F',
            rIsbn13      => 'A',
            rTitle       => 'B',
            rListPrice   => 'D',
            rRevenue     => 'I',
        },
        2 => {
            currencyCode           => 'H',
            countryCode            => 'K',
            dateBegin              => 'I',
            rIsbn13                => 'A',
            rTitle                 => 'B',
            rAuthor                => 'C',
            rImprint               => 'D',
            rListPrice             => 'G',
            rListPriceCurrency     => 'H',
            rPurchasePrice         => 'F',
            rPurchasePriceCurrency => 'H',
            rRevenue               => 'L',
        },
        3 => {
            dateBegin              => 'G',
            rTitle                 => 'C',
            rIsbn13                => 'B',
            countryCode            => 'I',
            rUnits                 => 'A',
            rListPrice             => 'E',
            rListPriceCurrency     => 'F',
            rPurchasePrice         => 'D',
            rPurchasePriceCurrency => 'F',
            rRevenue               => 'K',
            currencyCode           => 'F',
        },
        4 => {
            dateBegin              => 'J',
            rAuthor                => 'D',
            rTitle                 => 'C',
            rIsbn13                => 'B',
            rImprint               => 'E',
            countryCode            => 'L',
            rUnits                 => 'A',
            rListPrice             => 'H',
            rListPriceCurrency     => 'I',
            rPurchasePrice         => 'G',
            rPurchasePriceCurrency => 'I',
            rRevenue               => 'N',
            currencyCode           => 'I',
            rTaxUnitPrice          => 'G',
        },
    );

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

sub _unverifiedFieldMap {
    my $self               = shift;
    my %unverifiedFieldMap = (
        4 => {
            undiscountedRevenue => 'M',
            partnerShare        => 'O',
        },
    );
    return $unverifiedFieldMap{ $self->_version() };
}

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'agency' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType                { BookPub::DB::Item::Sale::kProductTypeEBook }

sub units {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue') || return;
    my $units   = 1;

    if ( $revenue < 0 ) {
        $units *= -1;
    }

    return $units;
}

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

    # 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;
    }
    elsif ( $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
        return $date;
    }

    # If it's not in the excel format, we need to test it against the month in the file name
    # to make sure we've got the order correct.
    my $filename = $self->filename;
    if ( $filename =~ /_(\w{3,9})\d{2}/ ) {
        my %textMonthVals = (
            "jan"       => 1,
            "january"   => 1,
            "feb"       => 2,
            "february"  => 2,
            "mar"       => 3,
            "march"     => 3,
            "apr"       => 4,
            "april"     => 4,
            "may"       => 5,
            "may"       => 5,
            "jun"       => 6,
            "june"      => 6,
            "jul"       => 7,
            "july"      => 7,
            "aug"       => 8,
            "august"    => 8,
            "sep"       => 9,
            "september" => 9,
            "oct"       => 10,
            "october"   => 10,
            "nov"       => 11,
            "november"  => 11,
            "dec"       => 12,
            "december"  => 12
        );
        my $month = $textMonthVals{ lc($1) };

        if ( $date && $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) {
            my $year = $1;

            if ( $month == $2 ) {
                return sprintf( "%04d-%02d-%02d", $year, $2, $3 );
            } elsif ( $month == $3 ) {
                return sprintf( "%04d-%02d-%02d", $year, $3, $2 );
            }
        }
    }

    $self->fail("Unable to verify date '$date' against date in file name");

}

sub _isSaleRec {
    my $self = shift;

    # We're going to check for the subtotal line, which only contains
    # totals for columns I and J.
    if (   $self->rRevenue
        && !$self->rIsbn13
        && !$self->rTitle
        && !$self->currencyCode
        && !$self->countryCode
        && !$self->dateBegin
        && !$self->rListPrice ) {
        return 0;
    }

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

1;
