package BookPub::Import::Importer::Christianaudio::Version7;

use strict;

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

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

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

sub _fieldMap {
    {
        # Header
        rProductType => 'D',

        # Data
        countryCode    => 'G',
        rState         => 'E',
        rPostalCode    => 'F',
        dateBegin      => 'C',
        rIsbn13        => 'J',
        rTitle         => 'D',
        rUnits         => 'O',
        rSales         => 'H',
        rReturns       => 'I',
        rListPrice     => 'K',
        rPurchasePrice => 'M',
        rRevenue       => 'P',
    };
}

sub priceType    { 'rrp' }
sub purchaseType { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub currencyCode { 'USD' }

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

    # date is in Excel format and is using 1904 as the epoch.  The third flag in the
    # ExcelFmt call below is setting the "is_1904_epoch" flag to true
    if ( $dateBegin =~ /(\d{5})\.(\d{11})/ || $dateBegin =~ /(\d{5})/ ) {
        $dateBegin = Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $dateBegin, 1 );
    }

    return $dateBegin;
}

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

    if ( length($field) > 0 ) {
        my $obj = Common::Country->Get($field);
        if ($obj) { return $obj->alpha2; }
    }
    return 'US';
}

sub _processHeader {
    my $self = shift;
    if ( $self->{_header1Found} ) { return }

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

    if ( $field =~ /audiobook/i ) {
        $self->{_productType}  = BookPub::DB::Item::Sale::kProductTypeAudioBook;
        $self->{_header1Found} = 1;
    }

    if ( $field =~ /ebook/i ) {
        $self->{_productType}  = BookPub::DB::Item::Sale::kProductTypeEBook;
        $self->{_header1Found} = 1;
    }

    if ( $field =~ /agency (\d{1,2})\%/i ) {
        $self->{_discount}     = $1;
        $self->{_header2Found} = 1;
        Log->info( "setting discount: " . $1 );
    }
}

sub productType {
    my $self = shift;

    return $self->{_productType};
}

sub rProductType {
    my $self = shift;

    return $self->{_productType};
}

sub rDiscount {
    my $self = shift;

    return $self->{_discount};
}

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