#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::RDAS::Process::ProductMonitor;

use Data::Dumper;

use lib '/app/tools/common/lib';
use Common::Assert;

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

use base 'BookPub::RDAS::Process';

sub _options {
    my $self    = shift;
    my $options = $self->SUPER::_options(@_);

    $options->{ebook_only} = {
        short       => 'e',
        description => 'Limit to only ebook products'
    };

    $options->{physical_only} = { description => 'Limit to only physical products' };

    $options->{book_id} = {
        short       => 'b',
        description => 'Limit to this book id',
        parameter   => 'i'
    };

    return $options;
}

sub _jobClass { 'BookPub::RDAS::Job::RunProductMonitor' }

sub _processService {
    my $self = shift;
    my $serviceID = shift || die;

    Log->notice("** Begin service process, Service ID: $serviceID");

    unless ( $self->param('physical_only') ) {
        Log->notice("  - Process eBooks Products");
        foreach my $book ( $self->_bookList($serviceID) ) {
            Log->notice( "*** Fetching info for book " . $book->BookID . " ***" );
            $self->_processProduct( serviceID => $serviceID, bookID => $book->BookID );
        }
    }

    unless ( $self->param('ebook_only') ) {
        Log->notice("  - Process Physical Products");
        foreach my $product ( $self->_productList($serviceID) ) {
            Log->notice( "*** Fetching info for product " . $product->ProductID . " ***" );
            $self->_processProduct( serviceID => $serviceID, productID => $product->ProductID );
        }
    }
}

sub _processProduct {
    my $self      = shift;
    my %args      = @_;
    my $serviceID = $args{serviceID};
    my $productID = $args{productID};
    my $bookID    = $args{bookID};

    assert($serviceID);
    assert( $productID || $bookID );

    # It looks like we were failing on a few requests due to network issues.
    # This just builds in a little retry.  Eventually this will be controlled using the throttler.

    my $numRetries = 1;

    while ( $numRetries > 0 ) {
        $numRetries--;

        eval {
            my $request = BookPub::RDAS::Request::ProductPrice->GetRequestObject( $serviceID, bookID => $bookID, productID => $productID );

            # !!! Is not having a request object something normal and expected?
            # !!! Or should we complain
            #

            $request->run() if ($request);
        };

        if ($@) {
            Log->error("$@");
            Log->error("Failed first request attempt, retry one time.");
            Log->info("Sleeping for 3 seconds before retry");
            sleep(3);
        } else {

            # Presumably it worked out ok...
            #
            last;
        }

    }

    # !!! Perhaps dying is what we want, EVENTUALLY, but for now (in dev) let's keep rolling...
    #
    if ($@) {
        Log->error(" Number of retries exceeded.  Going to blunder on ahead anyway...");

        #die "$@\n" if( $@ );
    }
}

sub _productList {
    my $self      = shift;
    my $serviceID = shift;

    my $productID = $self->param('product_id');
    my $limit     = $self->param('count');

    # Ignore physical if we specify book id
    return if ( $self->param('book_id') );

    my $request = BookPub::RDAS::Request::ProductPrice->GetRequestObject($serviceID);
    if ( !$request->includePhysicalProducts() ) {
        Log->info("   --  Service does not support physical products");
        return;
    }

    if ( defined($limit) && $limit <= 0 ) {
        Log->info("   --  Already exceded our record limit, not processing physical");
        return;
    }

    if ($productID) {
        my $book = new BookPub::Catalog::Product::Book( productID => $productID );
        if ( $book->isEBook() ) {
            Log->info(" - eBook Only. Ignoring physical product id $productID");
            return ();
        }

        return $book;
    }

    my $collection = BookPub::DB::Item::BookProduct->GetAllWithLimit( serviceID => $serviceID, limit => $limit, physicalOnly => 1 );

    Log->debug("* Get list of all products");

    my @list;

    while ( my $dbitem = $collection->next() ) {
        push( @list, new BookPub::Catalog::Product::Book( dbItem => $dbitem ) );
    }

    return @list;
}

sub _bookList {
    my $self      = shift;
    my $serviceID = shift;

    my $bookID = $self->param('book_id');
    my $limit  = $self->param('count');

    # Ignore ebooks if we specify product id
    if ( $self->param('product_id') ) {
        Log->info("   --  Product ID specified, not processing ebooks.");
        return ();
    }

    my $collection =
      BookPub::DB::Item::BookProduct->GetAllWithLimit( bookID => $bookID, serviceID => $serviceID, limit => $limit, groupEBook => 1 );

    Log->debug("* Get list of all ebooks");

    my @list;

    while ( my $dbitem = $collection->next() ) {
        push( @list, new BookPub::Catalog::Product::Book( dbItem => $dbitem ) );
    }

    if ( $self->param('count') ) {
        $self->{_count} = $self->{_count} - @list;
    }

    return @list;
}

1;
1;
