package BookPub::RDAS::Response::ProductPrice::BarnesNoble;

use lib '/app/tools/bookpub/lib';
use BookPub::DB::Item::BookProduct;
use BookPub::Catalog::Product::Book::WithPricing;
use base 'BookPub::RDAS::Response::ProductPrice';

sub serviceID { return BookPub::Tracker::Service::BARNES_NOBLE() }

sub _storeProductData {
    my $self = shift;

    $self->SUPER::_storeProductData();

    $self->_storeRank();
}

sub _getRankData {
    my $self = shift;
    return { rank => $self->parser->Rank() };
}

sub _storeRank {
    my $self = shift;

    die "No rank" unless ( $self->productID );

    my $rank = new BookPub::RDAS::Form::ProductMonitor::ProductMonitorItem::Rank(
        serviceID => $self->serviceID,
        productID => $self->productID
    );

    my $websiteData = $self->_getRankData();

    if ( $rank->requiresUpdate($websiteData) ) {
        $rank->create($websiteData);

        my $currencyCode = 'USD';
        my $countryCode  = 'US';
        my $product      = new BookPub::Catalog::Product::Book::WithPricing( productID => $self->productID );
        my $price        = $product->getPriceByCurrency($currencyCode);

        BookPub::DB::Item::BookProduct->UpdateAverageRank(
            product_id    => $self->productID,
            currency_code => $currencyCode,
            country_code  => $countryCode,
            price         => $price->Price()
        );

    } else {
        $rank->updateTimestamp();
    }
}

sub _getMetadata {
    my $self   = shift;
    my $fields = {
        isbn10  => $self->parser->ISBN10(),
        isbn13  => $self->parser->ISBN13(),
        title   => $self->parser->Title(),
        authors => $self->parser->Author(),
    };

    return $fields;
}

sub _getPriceData {
    my $self = shift;

    my $fields = { price => $self->parser->ProductPrice() || $self->parser->EBookPrice(), };

    return $fields;
}

sub _getCoverArtData {
    my $self = shift;

    my $fields = { cover_art_url => $self->parser->CoverURL(), };

    return $fields;
}

1;
