package RT::Groups;

use strict;
no warnings 'redefine';

sub LimitToRolesForGroup {
    my ( $self, $group ) = @_;
    $self->Limit(
	FIELD    => 'Domain',
	OPERATOR => '=',
	VALUE    => 'RT::Group-Role'
    );

    $self->Limit(
	FIELD    => 'Instance',
	OPERATOR => '=',
	VALUE => $group
    ) if $group;
}

sub RoleMap {
    my $self = shift;
    require YAML;
    return eval {
	YAML::Load( $RT::SystemUser->Attribute( $self->RoleMapKey ) )
    } || {};
}

sub SetRoleMap {
    my ( $self, $list ) = @_;
    require YAML;
    $RT::SystemUser->SetAttribute( $self->RoleMapKey, YAML::Dump($list) );
}

sub RoleMapKey { 'RoleMap' }

sub HRMSUserDefinedGroups {
    my ( $self, $CurrentUser ) = @_;
    my @rv;

    my $Groups = RT::Groups->new( $CurrentUser || $self->CurrentUser );
    $Groups->LimitToUserDefinedGroups;
    $Groups->Limit(
	FIELD    => 'Name',
	OPERATOR => 'IS NOT',
	VALUE    => 'NULL'
    );
    $Groups->OrderByCols(
	{ FIELD => 'SIGN(Description)', ORDER => 'ASC'},
	{ FIELD => 'Name' }
    );
    return $Groups;
}

sub LimitToInactive {
    my $self = shift;
    $self->LimitToActive(@_, NEGATE => 1);
}

sub LimitToActive {
    my $self = shift;
    my ($day, $mon, $year) = (localtime(time))[3, 4, 5];
    $mon++; $year += 1900;
    my $date = sprintf("%04s/%02s/%02s", $year, $mon, $day);

    $self->LimitAttribute(
	@_,
	NAME	    => 'Starts',
	OPERATOR    => '<=',
	VALUE	    => $date,
	EMPTY	    => 1,
	NULL	    => 1,
    );
    $self->LimitAttribute(
	@_,
	NAME	    => 'Due',
	OPERATOR    => '>=',
	VALUE	    => $date,
	EMPTY	    => 1,
	NULL	    => 1,
    );
}

sub LimitToDisabled {
    my $self = shift;
    $self->LimitToEnabled(@_, NEGATE => 1);
}

sub LimitToEnabled {
    my ($self, %args) = @_;
    
    my $alias = $self->Join(
	TYPE   => 'left',
	ALIAS1 => ($args{ALIAS} || 'main'),
	FIELD1 => 'id',
	TABLE2 => 'Principals',
	FIELD2 => 'ObjectId',
    );

    return $self->Limit(
	ALIAS => $alias,
	FIELD => 'Disabled',
	OPERATOR => ($args{NEGATE} ? '!=' : '='),
	VALUE => '0',
	ENTRYAGGREGATOR => 'OR'
    ) if !$args{ALIAS};

    $self->Limit(
	LEFTJOIN => $alias,
	FIELD => 'Disabled',
	OPERATOR => '!=',
	VALUE => '0',
    );

    $self->Limit(
	%args,
	ALIAS => $alias,
	FIELD => 'id',
	OPERATOR => ($args{NEGATE} ? 'IS NOT' : 'IS'),
	VALUE => 'NULL',
    );
}

sub LimitToPersonalGroups {
    my $self = shift;
    $self->Limit(
	@_,
	FIELD => 'Domain',
	OPERATOR => '=',
	VALUE => 'Personal',
    );
}

sub LimitToDelegateTo {
    my $self = shift;
    my $princ = shift;

    $self->Limit(
	@_,
	FIELD => 'Description',   
	OPERATOR => '=', 
	VALUE => $princ,
	ENTRY_AGGREGATOR => 'OR',
    );
}

sub LimitToDelegateOnGlobal {
    my $self = shift;
    $self->RT::Groups::LimitToDelegateOnQueue(-1, @_);
}

sub LimitToDelegateOnQueue {
    my $self = shift;
    my $queue = shift;

    $self->Limit(
	@_,
	FIELD	    => 'Name',
	OPERATOR    => '=',
	VALUE	    => $queue,
    );
}

1;
