#!/usr/bin/perl

use strict;
use warnings;
$| = 1;

package API::RSLDaemon;

use Date::Format ();
use Time::HiRes ();

use lib qw(libs);
use API::Config ();
use API::Utils::WorkQueue ();
use base 'API::Utils::WorkQueue';

use lib ($API::Config::Config->{'Website_libs'});
use ECS::Site;
use ECS::Stocking;
use ECS::DB;

# it might be possible to use multiple threads later if we can find
# a good way to determine which products can safely be modified
# at the same time as one another
$API::Utils::WorkQueue::NUM_THREADS = 1;
$API::Utils::WorkQueue::PERSISTENCE_FILENAME = "/tmp/.rsl_queue";
$API::Utils::WorkQueue::WORK = \&save;

return 1;

###############################################################################

sub save {
    my $data = shift;
    my $t0 = Time::HiRes::time;

    printf("[%s] - - - Beginning to process %s \n", (
        scalar localtime,
        $data->{'productID'},
    ));

    my $site = ECS::Site->fromName('ECS');

    # run new rsl for product.
    ECS::Stocking::calcStockingByProduct({
        'DBH' => {
            'MASTER' => $site->estore_dbh,
            'SLAVE' => $site->estore_dbhr,
        },
        'productID' => $data->{'productID'},
    });

    printf("[%s] - - - Took %.03fs to process %s \n", (
        scalar localtime,
        Time::HiRes::time - $t0,
         $data->{'productID'},
    ));

#    $site->estore_dbh->disconnect();
#    $site->estore_dbhr->disconnect();
    ECS::DB->dbDisconnectAllHandles();
    return 1;
}

###############################################################################


