package BookPub::Import::Importer::Bookshop::v1;

use strict;
use warnings;

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


sub _fieldMap {
    {
        dateBegin          => 'H',
        dateEnd            => 'H',
        rAuthor            => 'M',
        rTitle             => 'L',
        rIsbn13            => 'K',
        rState             => 'C',
        rPostalCode        => 'G',
        countryCode        => 'B',
        rUnits             => 'N',
        rListPrice         => 'O',
        rListPriceCurrency => 'Q',
        rDiscount          => 'P',
        rRevenue           => 'AC',
        currencyCode       => 'Q',
        rTaxAmount         => 'AA',

    }
}

sub _unverifiedFieldMap {
    {
        "_main_product_id_type" => 'J'
    }
}

sub _headerIdentifier { rTitle => 'product_title' }

sub rServiceName  { 'Bookshop' }
sub priceType     { 'agency' }
sub _useIsSaleRec { 1 }
sub purchaseType  { BookPub::DB::Item::Sale::kPurchaseTypeDownload }
sub productType { BookPub::DB::Item::Sale::kProductTypeEBook }

sub dateBegin {
    my $self = shift;

    my $date = $self->_getByFieldName('dateBegin') || '';
    my ($d, $m, $y);

    # YYYYMMDD
    if ( ($y, $m, $d) = $date =~ /(\d{4})(\d{2})(\d{2})$/) {
        return sprintf "%04d-%02d-%02d", $y, $m, $d;
    }

    $self->fail("dateBegin '$date' is not in correct format");
}

sub dateEnd {
    my $self = shift;

    my $date = $self->_getByFieldName('dateEnd') || '';
    my ($d, $m, $y);

    # YYYYMMDD
    if ( ($y, $m, $d) = $date =~ /(\d{4})(\d{2})(\d{2})$/) {
        return sprintf "%04d-%02d-%02d", $y, $m, $d;
    }

    $self->fail("dateEnd '$date' is not in correct format");
}

sub isFree {
    my $self = shift;

    return (((!$self->rRevenue || $self->rRevenue =~ /^0.0+/) && $self->rUnits) ? 'Y' : 'N');
}

sub rIsbn13 {
    my $self = shift;

    my $type = $self->_getByFieldName('_main_product_id_type') || "";
    my $isbn13 = $self->_getByFieldName('rIsbn13') || "";

    return $isbn13 if ($type =~ /^ISBN.13$/i);

    $self->fail("main_product_id_type ('$type') is not ISBN-13");
}

1;
