package BookPub::Import::Importer::BookShout::Base;

use strict;
use Data::Dumper;

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

sub _headerIdentifier { ( rTitle => 'Product title' ) }
sub _autoParseTitleAndSubtitle { 1 }
sub _useIsSaleRec              { 1 }
sub purchaseType               { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub _dateFormat                { ['iso'] }

sub priceType {
    my $self = shift;
    my $type = $self->_getByFieldName('rPriceType');

    if ( !$type && defined $self->_getByFieldName('altPriceType') ) {
        $type = $self->_getByFieldName('altPriceType');
    }

    if ( $type eq '01' || $type eq '1' || $type eq '02' || $type eq '11' ) {
        return 'rrp';
    }

    if ( $type eq '41' || $type eq '43' ) {
        return 'agency';
    }

    my $clientID = Common::RSApp::GetClientID();
    if ( !$type && $clientID == 346 ) {    # Setting RRP as the default for RLPG
        return 'rrp';
    }

    $self->fail("Unknown price type '$type'");
}

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

    my $useThis = $date && length($date) > 0 ? $date : $date2;
    if ( $useThis =~ m/(\d{4})(\d{2})(\d{2})/ ) {
        return $1 . '-' . $2 . '-' . $3;
    }
}

sub _getDateEnd {
    my $self  = shift;
    my $date  = $self->_getByFieldName('dateEnd');
    my $date2 = $self->_getByFieldName('dateEnd2');

    my $useThis = $date && length($date) > 0 ? $date : $date2;
    if ( $useThis =~ m/(\d{4})(\d{2})(\d{2})/ ) {
        return $1 . '-' . $2 . '-' . $3;
    }
}

sub productType {
    my $self = shift;
    my $type = $self->_getByFieldName('rProductType');

    if ( $type eq '15' ) {
        return BookPub::DB::Item::Sale::kProductTypeEBook;
    }

    $self->fail("Unknown product type '$type'");
}

sub rFormat { shift->_getByFieldName('rFormat') }

sub rIsbn13 {
    my $self  = shift;
    my $title = $self->_getByFieldName('rTitle');
    my $isbn  = $self->_getByFieldName('isbn');

    if ( !$title && !$isbn ) {
        $self->fail("Sale is missing both title and ISBN");
    }

    return $isbn;
}

sub _isSaleRec {
    my $self = shift;

    # Only process sales on sheet 1
    if ( $self->sheetnum != 1 ) { return }

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

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