#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2010 RoyaltyShare, Inc.      All Rights Reserved
#---------------------------------------------------------------
package Job::RuleList;

use strict;
use Data::Dumper;

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

use lib '/app/tools/job/lib';
use Job::DB::Item::JobRunRule;
use Job::RunRule;
use Job::SkipRuleList;

use base 'Common::XMLObject';

# This class will generate a list of rules that are allowed to run on this host.
# The results are cached and are updated automatically if changes are detected in
# the database.
#
# These rules will then be used to generate the where clause.

sub _init {
    my ( $self, %args ) = @_;

    $self->SUPER::_init(%args);

    assert( $args{hostname}, "Hostname required" );

    $self->{_hostname} = $args{hostname};

    $self->refresh();

    return $self;
}

sub refresh {
    my $self = shift;

    my $cacheTableMD5 = Job::DB::Item::JobRunRule->getTableMd5( $self->{_last_table_md5} );

    # This means there has been an update since we last checked the cache
    unless ( $cacheTableMD5 == $self->{_last_table_md5} ) {
        Common::Log::Debug("Refreshing ruleset cache");
        $self->{Rule} = [];

        my $collection = Job::DB::Item::JobRunRule->GetAllForHostname( $self->{_hostname} );

        while ( my $obj = $collection->next() ) {
            my $rule = Job::RunRule->new( dbItem => $obj );

            push( @{ $self->{Rule} }, $rule );
        }

        $self->_addExceptions();

        $self->{_last_table_md5} = $cacheTableMD5;

        #Common::Log::Debug( "RESULT: \n" . Dumper $self->{Rule} );
    }
}

# This method iterates through the rules to find general rules and adds exceptions
# to the rule.  The exception makes it so that the more specific rules override
# the general rules.
sub _addExceptions {
    my $self = shift;

    foreach my $rule ( @{ $self->{Rule} } ) {
        $rule->logRule();

        # Look for more specific rules.  If found then add an exception to the rule.
        foreach my $otherRule ( @{ $self->{Rule} } ) {
            $self->_addRuleException( $rule, $otherRule );
        }
    }
}

sub _addRuleException {
    my $self      = shift;
    my $rule      = shift;
    my $otherRule = shift;
    my %exception;

    my $clientID = $rule->ClientID;
    my $class    = $rule->Class;
    my $subclass = $rule->Subclass;

    my $otherClientID = $otherRule->ClientID;
    my $otherClass    = $otherRule->Class;
    my $otherSubclass = $otherRule->Subclass;

    assert( $rule && $otherRule, "two rules are required" );

    # Class is required and if they don't match this rule can't be a generaliztion
    # of the other rule.
    return unless ( $class eq $otherClass );

    # If clientID and subclass are defined then this is the most specific it can be
    return if ( defined($clientID) && defined($subclass) );

    if ( !defined($clientID) && defined($otherClientID) ) {
        $exception{clientID} = $otherClientID;
    }

    if ( !defined($subclass) && defined($otherSubclass) ) {
        $exception{subclass} = $otherSubclass;
    }

    if (%exception) {

        # !!! Hopefully this won't leak.
        # !!! I need to store a back-reference to the original rule, so I can
        # !!! check later to see whether there are any maxed client ids that
        # !!! need to be added to the sql clause.
        # !!! I don't have that info yet... not until the RunStatus object goes over the rules.
        #
        if ( $rule->ClientMax() > $otherRule->ClientMax() ) {
            $exception{otherRule} = $otherRule;
        }
        $rule->addException( \%exception );
    }
}

sub Rules {
    my $self = shift;
    $self->refresh();
    return $self->{Rule};
}

1;
