package BookPub::Import::Importer::HBG::Version4;

use strict;

use base 'BookPub::Import::Importer::HBG::Version1';

sub _fieldMap {
    {
        rServiceName       => 'B',
        dateBegin          => 'D',
        dateEnd            => 'D',
        rAuthor            => 'L',
        rTitle             => 'O',
        rIsbn10            => 'K',
        rIsbn13            => 'J',
        countryCode        => 'A',
        rUnits             => 'T',
        rListPrice         => 'P',
        rListPriceCurrency => 'U',
        rRevenue           => 'U',
        currencyCode       => 'U',
        rChannel           => 'H',
    };
}

sub _headerIdentifier { rAuthor => 'Author' }
sub productType       { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rProductType      { BookPub::DB::Item::Sale::kProductTypeEBook }
sub rDistributor      { 'HBG' }
sub _getDateEnd       { shift->_getDateBegin }

sub rUnits { $_[0]->_getByFieldName('rUnits') =~ s/\..+//r }

sub countryCode {
    my $self = shift;

    my $countryCode = $self->_getByFieldName('countryCode') || "";
    my $service = $self->_getByFieldName('rServiceName') || "";

    return $countryCode if $countryCode;

    my %countryMap = (
        "AMAZON DIGITAL .CA" => "CA",
        "AMAZON DIGITAL CANADA" => "CA",
        "APPLE INC - CANADA SALES" => "CA",
        "GOOGLE CANADA EBOOKS" => "CA",
        "KOBO CANADA EBOOKS" => "CA",
        "AMAZON DIGITAL" => "US",
        "APPLE INC E-BOOK" => "US",
        "BARNES & NOBLE EBOOKS" => "US",
        "EBOOKS.COM INTNATL LLC." => "US",
        "KOBO EBOOKS" => "US",
        "GOOGLE EBOOKS" => "US",
        "REDSHELF" => "US",
    );

    return $countryMap{$service} if exists($countryMap{$service});

    $self->fail("Unknown country code '$countryCode' for service '$service'");
}

sub _isSaleRec {
    my $self = shift;

    my $date    = $self->_getByFieldName('dateBegin');
    my $units   = $self->_getByFieldName('rUnits');
    my $revenue = $self->_getByFieldName('rRevenue');

    return $date && defined $units && defined $revenue;
}

1;
