package Job::JobRuleSet;

use strict;
use Data::Dumper;
use XML::Simple;
use lib '/app/tools/common/lib';
use Common::XMLObject;
use Common::FormHash;

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

use base 'Common::FormHash';

sub _tagName {
    return 'JobRule';
}

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

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

    return $collection;
}

sub _addObject {
    my ( $self, $object ) = @_;

    if ( $self->{_hostname} ) {

        # If we already _have_ a virtually identical rule, then the rule who's hostname
        # matches our hostname wins.
        # This is so we can 'overload' the 'hostname' column to contain host_class.
        #
        my $hash = $self->{'JobRule'};
        foreach my $key ( keys %$hash ) {
            my $currentObj = $hash->{$key};

            # !!! Note: This logic will not allow you to have a similar rule set up
            # !!! for multiple host_classes.   So, don't create stupidly generic
            # !!! rules for host classes...
            #
            if (   $object->ClientID() eq $currentObj->ClientID()
                && $object->Class() eq $currentObj->Class()
                && $object->Subclass() eq $currentObj->Subclass() ) {
                if ( $object->Hostname() ne $self->{_hostname} ) {

                    # The new object looses.
                    #
                    return;
                }

                # Delete the old rule.
                # The new rule will take it's place.
                #
                delete $hash->{$key};

                # Don't really need to keep looping...
                #
                last;
            }
        }
    }

    $self->SUPER::_addObject($object);
}

sub _keyMethodName {
    return 'JobRunRuleID';
}

sub _getNewObject {
    my ($self) = @_;

    if ( $self->{_hostname} ) {
        return Job::RunRule->new( hash => { hostname => $self->{_hostname} } );
    }

    return Job::RunRule->new();
}

sub _getObjectFromDBItem {
    my ( $self, $dbItem ) = @_;
    return Job::RunRule->new( dbItem => $dbItem );
}

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

    if ( $args{hostname} ) {
        $self->{_hostname} = $args{hostname};
    }

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

sub getRules {
    my ($self) = @_;
    return $self->{JobRule};
}

sub save {
    my ($self) = @_;

    my $keys = $self->getKeys();

    foreach my $id (@$keys) {
        my $rule = $self->{JobRule}{$id};
        $rule->save();
    }
}

1;
