#!/usr/bin/perl
#
# Script to launch jobs to build sale aggregates for all clients.
#

use strict;

AggBuilder->start();

package AggBuilder;

use lib '/app/tools/common/lib';
use Common::Session;
use Common::Consts qw(%CLIENT_SALE_AGG);

use lib '/app/tools/stats/lib';
use Stats::Job::Build;

use lib '/app/tools/rps/lib';
use base 'RPS::CronScript';

sub _options {
    {
        force => {
            short       => 'f',
            description => 'Force rebuild of aggregates'
        }
    };
}

sub _process {
    my $self = shift;
    my $id   = Common::RSApp::GetClientID();

    my $jobArgs = Stats::Job::Build->new( clientID => $id, force => $self->{_force} );
    my $job = $jobArgs->enqueue();
}

sub _get_client_list {
    my $self = shift;
    my @list = $self->SUPER::_get_client_list(@_);
    my @result;

    my $dbx = Common::Session::getdbx('admindb');
    my $rset = $dbx->resultset('Report::DDb')->search( { 'calc_stat' => 1, 'client_type' => 'RPS' } );
    while ( my $row = $rset->next ) {
        push @result, $row->client_id;
    }

    #    foreach my $client_id ( sort by_priority keys %CLIENT_SALE_AGG ) {
    #        next unless $CLIENT_SALE_AGG{$client_id}->{active};
    #        next unless grep( /^$client_id$/, @list );
    #
    #        push( @result, $client_id );
    #    }

    return @result;
}

sub by_priority {
    $CLIENT_SALE_AGG{$a}->{priority} <=> $CLIENT_SALE_AGG{$b}->{priority};
}
