package BookPub::Import::Importer::Copia::Version3;

use strict;

use lib '/app/tools/common/lib';
use Common::Util;

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

sub _fieldMap {
    {
        currencyCode           => 'G',
        countryCode            => 'I',
        rState                 => 'J',
        rPostalCode            => 'N',
        dateBegin              => 'AA',
        rProductType           => 'AV',
        isbn                   => 'AF',
        rTitle                 => 'AI',
        rAuthor                => 'AJ',
        rImprint               => 'AN',
        rUnits                 => 'AO',
        rListPrice             => 'CI',
        rListPriceCurrency     => 'AT',
        rPurchasePrice         => 'AP',
        rPurchasePriceCurrency => 'AT',
        rTaxAmount             => 'BU',
        rDiscount              => 'AQ',
        rRevenue               => 'CK',
    };
}

sub _useIsSaleRec { 1 }

sub _headerIdentifier { ( rTitle => 'Product title' ) }
sub purchaseType      { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceType         { 'agency' }

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

    if ( $code =~ m/^\-(\d{5})$/ ) {
        $code = $1;
    } elsif ( $code =~ m/^(\d{5})\-0{1,3}$/ ) {
        $code = $1;
    }
    return $code;
}

sub productType {
    my $self = shift;

    my $productType = $self->_getByFieldName('rProductType');

    if ( lc($productType) eq 'ebook' || 'epub' ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    } else {
        $self->fail("Unknown product type: $productType");
        return undef;
    }
}

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;
    }

    # new case with date reported as YYYYMMDD
    if ( $date && $date =~ /^(\d{4})(\d{2})(\d{2})$/ ) {
        return sprintf( "%04d-%02d-%02d", $1, $2, $3 );
    }

    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;    # Play nicely.
###
