package BookPub::Import::Importer::HBG::Version1;

use strict;

use lib '/app/tools/common/lib';
use Date::Calc qw( Add_Delta_YM );

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

sub _headerIdentifier { ( rAuthor => 'Author' ) }

sub _fieldMap {
    {
        rServiceName         => 'C',
        countryCode          => 'A',
        dateBegin            => 'D',
        rIsbn13              => 'J',
        rIsbn10              => 'K',
        rTitle               => 'O',
        rAuthor              => 'L',
        rUnits               => 'Q',
        rListPrice           => 'P',
        rRevenue             => 'R',
        rChannel             => 'I',
        rTransactionCategory => 'F',
    };
}

sub purchaseType       { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub priceType          { 'agency' }
sub currencyCode       { 'USD' }
sub rListPriceCurrency { 'USD' }
sub productType        { BookPub::DB::Item::Sale::kProductTypeEBook }
sub _useIsSaleRec      { 1 }

sub _processLine {
    my $self  = shift;
    my $price = $self->rListPrice();

    if ( ( $price && $price =~ m/Total/ ) || ( !$price ) ) {
        $self->{_endOfData} = 1;
    }

    return $self->SUPER::_processLine(@_);
}

sub _isSaleRec {
    my $self = shift;

    # If we've set the end of data flag in processLine, we are done.
    return if ( $self->{_endOfData} );

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

sub serviceID {
    my $self = shift;
    my $name = $self->rServiceName();

    if ( defined($name) ) {
        my $id = BookPub::Tracker::Service::GetServiceIDByName($name)
          || $BookPub::Import::Importer::HBG::ServiceMap::SERVICE_ALIASES{ lc $name };

        if ($id) {
            return $id;
        } else {
            $self->fail("Unknown service name '$name'");
        }
    }

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

sub rTitle {
    my $self = shift;

    my $title = $self->SUPER::rTitle();
    $title =~ s/\(Open Ebook\)//i;

    return $title;
}

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

    if ( $date && ( $date =~ /(\d{4})-(\d{2})-(\d{2})/ ) ) {
        my ( $year, $month, $day ) = Add_Delta_YM( $1, $2, $3, 0, -1 );
        return sprintf( "%04d-%02d-%02d", $year, $month, $day );
    } elsif ( $date =~ /(\d{5})/ ) {
        return Spreadsheet::ParseExcel::Utility::ExcelFmt( "yyyy-mm-dd", $date);
    } else {
        $self->fail( "Couldn't determine date from: " . $date );
    }
}

1;
