package BookPub::Import::Importer::Amazon::Version23;

use strict;

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

use Date::Calc qw( Add_Delta_YM );

sub _headerIdentifier { ( currencyCode => 'Payment Amount Currency' ) }

sub _fieldMap {
    {
        serviceProductID   => 'H',
        currencyCode       => 'U',
        dateBegin          => 'C',
        rFormat            => 'K',
        rIsbn13            => 'F',
        rTitle             => 'G',
        rAuthor            => 'I',
        rImprint           => 'J',
        rUnits             => 'N',
        rListPrice         => 'Q',
        rListPriceCurrency => 'R',
        rPurchasePrice     => 'O',
        rDiscount          => 'S',
        rRevenue           => 'T',
    };
}

sub countryCode  { 'US' }
sub priceType    { 'agency' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType  { BookPub::DB::Item::Sale::kProductTypeEBook }

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

    return $discount;
}

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

    if ( $currencyCode =~ /(\w{3})/ ) {
        $currencyCode = $1;
    }

    return $currencyCode;
}

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

    # The date is being returned in this format: 16-DEC-2012 14:16:18
    # I don't even...
    #
    if ( $date =~ /(\d{2})-(\w{3})-(\d{4})/ ) {

        my $day       = $1;
        my $monthAbbr = uc($2);
        my $year      = $3;

        my %monthAbbrToNumber;
        $monthAbbrToNumber{"JAN"} = 1;
        $monthAbbrToNumber{"FEB"} = 2;
        $monthAbbrToNumber{"MAR"} = 3;
        $monthAbbrToNumber{"APR"} = 4;
        $monthAbbrToNumber{"MAY"} = 5;
        $monthAbbrToNumber{"JUN"} = 6;
        $monthAbbrToNumber{"JUL"} = 7;
        $monthAbbrToNumber{"AUG"} = 8;
        $monthAbbrToNumber{"SEP"} = 9;
        $monthAbbrToNumber{"OCT"} = 10;
        $monthAbbrToNumber{"NOV"} = 11;
        $monthAbbrToNumber{"DEC"} = 12;

        my $month = $monthAbbrToNumber{$monthAbbr};

        $date = $year . "-" . $month . "-" . $day;
    } elsif ( $date =~ /(\d{2})\/(\d{2})\/(\d{4})/ ) {

        # Great news! It's now coming in as: 31/03/2013 03:03:20 PM
        # So we'll deal with that now, too.
        $date = $3 . "-" . $2 . "-" . $1;
    }

    return $date;
}

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $title;
}

sub rSubtitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    my $subtitle;
    ( $title, $subtitle ) = BookPub::Import::Importer::ParseTitleAndSubtitle($title);

    return $subtitle;
}

1;
