#!/usr/bin/perl
#------------------------------------------------------------
# Copyright (C) 2010 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------
use strict;

RunController->start();

package RunController;

use lib '/app/tools/common/lib';
use lib '/app/tools/job/lib';

use Job::Job::TestParent;
use Job::Job::TestChild;

use base 'Common::Script';

sub _options {
    {
        parent => {
            short       => 'p',
            description => 'Create the parent job'
        },
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'Limit to this client id',
            parameter   => 'i'
        },
        count => {
            short       => 'n',
            default     => 50,
            description => 'Number of child jobs to create',
            parameter   => 'i'
        },
    };
}

sub _process {
    my $self = shift;

    if ( $self->param('parent') ) {
        $self->_createParentJob();
    } else {
        $self->_createChildJobs();
        $self->_listener();
    }
}

sub _createParentJob {
    my $self = shift;
    my $job  = new Job::Job::TestParent(
        clientID   => $self->param('client_id'),
        childCount => $self->param('count')
    );
    $job->enqueue();
}

sub _createChildJobs {
    my $self = shift;
    my %jobs;

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

    for ( my $i = 0 ; $i < $count ; $i++ ) {
        my $job = new Job::Job::TestChild();
        $job->enqueue();
        $jobs{ $job->id() } = $job;
    }

    $self->{_jobStatus} = \%jobs;
}

sub _listener() {
    my $self  = shift;
    my $jobs  = $self->{_jobStatus};
    my $count = scalar keys(%$jobs);

    while ( my $incomplete = $self->_checkForComplete() ) {
        $self->debug( "Waiting for children. (" . $incomplete . " of $count remaining)" );
        sleep(5);
    }
}

sub _checkForComplete {
    my $self       = shift;
    my $jobs       = $self->{_jobStatus};
    my $incomplete = 0;

    foreach my $jobID ( keys %$jobs ) {
        my $job = $jobs->{$jobID};
        next unless ($job);

        my $jobStatus = $job->getStatus();

        if ( Job::Status::kComplete eq $jobStatus || Job::Status::kDead eq $jobStatus ) {
            $jobs->{$jobID} = undef;
        } else {
            $incomplete++;
        }
    }

    return $incomplete;
}

1;
