package BookPub::Import::Importer::AmazonPOD;

use strict;
use Date::Calc qw(Days_in_Month);

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

sub _headerIdentifier { ( rIsbn10 => 'ISBN' ) }

# map version num to the field order
sub _fieldMap {
    my $self = shift;

    my %fieldMap = (
        43 => {
            countryCode => 'A',
            rIsbn10     => 'C',
            rIsbn13     => 'D',
            rTitle      => 'G',
            rAuthor     => 'F',
            rImprint    => 'E',
            rUnits      => 'H',
            rFee        => 'N',
            rListPrice  => 'I',
            rDiscount   => 'K',
            rRevenue    => 'M',
            rChannel    => 'A',
        },
        44 => {
            countryCode => 'A',
            rIsbn10     => 'C',
            rIsbn13     => 'D',
            rTitle      => 'G',
            rUnits      => 'H',
            rFee        => 'N',
            rListPrice  => 'I',
            rDiscount   => 'K',
            rRevenue    => 'M',
            rChannel    => 'A',
        },
    );

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

sub _useIsSaleRec              { 1 }
sub _autoParseTitleAndSubtitle { 1 }
sub priceType                  { 'rrp' }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypePrintOnDemand }
sub productType                { BookPub::DB::Item::Sale::kProductTypePhysicalBook }

sub currencyCode {
    my $self        = shift;
    my $countryCode = $self->countryCode();

    my %countryToCurrency;
    $countryToCurrency{'DE'} = 'EUR';
    $countryToCurrency{'JP'} = 'GBP';
    $countryToCurrency{'UK'} = 'GBP';
    $countryToCurrency{'US'} = 'USD';

    if ( $countryToCurrency{ uc($countryCode) } ) {
        return $countryToCurrency{ uc($countryCode) };
    } else {
        $self->fail( "Couldn't determine currency code from country code: " . $countryCode );
    }
}

sub rListPriceCurrency {
    my $self = shift;

    return $self->currencyCode();
}

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

    if ( $countryCode =~ /Amazon (\w{2}) /i ) {
        return $1;
    } else {
        $self->fail( "Couldn't determine country code from " . $countryCode );
    }
}

sub rRevenue {
    my $self    = shift;
    my $revenue = $self->_getByFieldName('rRevenue');
    $revenue =~ s/,//g;

    return $revenue;
}

sub rDiscount {
    my $self = shift;
    my $discount = $self->_getByFieldName('rDiscount') || return;
    $discount =~ s/%//;
    $discount = ( 100 - $discount ) / 100;
    return $discount;
}

sub _getDateBegin {
    my $self = shift;

    my $date;

    # If dateBegin is defined in the fieldmap, we'll use that,
    # Otherwise, we'll default to the date from the header.
    if ( defined $self->_getByFieldName('dateBegin') ) {
        $date = $self->_getByFieldName('dateBegin');
    } else {
        $date = $self->{_headerDate};
    }

    # Need to normalize this range to the start and end dates of the first month
    if ( $date =~ /(\d{2})\/\d{2}\/(\d{2})$/ ) {
        my $month = $1;
        my $year  = $2;
        $date = "20" . $year . "-" . $month . "-" . "01";
    } elsif ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
    }

    return $date;
}

sub _getDateEnd {
    my $self = shift;

    my $date;
    if ( defined $self->_getByFieldName('dateBegin') ) {
        $date = $self->_getByFieldName('dateBegin');
    } else {
        $date = $self->{_headerDate};
    }

    # Need to normalize this range to the start and end dates of the first month
    if ( $date =~ /(\d{2})\/\d{2}\/(\d{2})$/ ) {
        my $month = $1;
        my $year  = $2;
        $date = "20" . $year . "-" . $month . "-" . Days_in_Month( $year, $month );
    } elsif ( $date =~ /^\d{5}$/ and $date > 38716 ) {
        $date = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date );
    }

    return $date;
}

sub _isSaleRec {
    my $self = shift;

    my $country = $self->_getByFieldName('countryCode');
    my $isbn10  = $self->_getByFieldName('rIsbn10');
    my $isbn13  = $self->_getByFieldName('rIsbn13');
    my $title   = $self->_getByFieldName('rTitle');

    # We're going to skip the subtotal line, which is blank for these fields
    if ( ( !$country && !$isbn10 && !$isbn13 && !$title ) || ( $country == '' && $isbn10 == '' && $isbn13 == '' && $title == '' ) ) {
        return 0;
    }

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

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

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

    foreach my $sheet ( @{ $args{sheets} } ) {
        foreach my $line (@$sheet) {

            # Since we're at the preProcess stage, it seems we have to reference rows by number.
            my $dateCell = $line->[1];
            if ( $dateCell =~ m/(\d{2}\/\d{2}\/\d{2}) to \d{2}\/\d{2}\/\d{2}/i ) {
                $self->{_headerDate} = "$1";
                last;
            }
        }
    }
}

1;
