package RT::Record;


# FIXME : maybe replace this property by an attribute,
# using AddAttribute

sub QParent {
    my $self = shift;
    #warn "Calling parent @_";
    my $template_name ='Parent';
    my $value = shift;

    my ($attr) = $self->Attributes->Named($template_name);
    return if ! $attr and ! defined $value;

    if (length $value and defined $value) {
	$self->SetAttribute( Name => $template_name, Content => $value );
	$attr = $self->Attributes->Named($template_name);;
	$self->_QParent($value);
    }

    return $attr->Content;
}

sub SetQParent {
    shift->QParent(@_);
}

sub _QParent {
    my $self = shift;
    if (@_) {
	$self->{'_QParent'} = shift;
    }
    return $self->{'_QParent'};
}

sub _QParentObj {
    my $self = shift;
    if (@_) {
	$self->{'_QParentObj'} = shift;
    }
    return $self->{'_QParentObj'};
}

=head2 getQParent()

Returns an object (caller's class) if $self::QParent is not null.

=cut

sub getQParent {
    my $self = shift;

    # warn "Calling getQParent on ".$self->id()." (name : ".$self->Name.")\n";

    return if ! $self->QParent;
    return $self->_QParentObj if $self->_QParentObj;

    my $class = ref($self);
    my $queue = $class->new($self->CurrentUser);
    my $qid = $queue->Load($self->QParent); # FIXME : the term "queue" is inappropriate

    if (! $qid) {
        return ( 0, $self->loc('Queue could not be created') ); # FIXME : the error message is not relevant
    }

    $self->_QParentObj($queue);
    return $queue;
}

=head3 Genealogie : [ objs ]

Returns all the object's parents (and grand-parents, and ...).

=cut

sub Genealogie {
    my $self = shift;

    my $ancestors = [];
    my $parent = $self->getQParent;
    return [ $self ] if ! $parent;

    # warn "Calling genealogie on ".$self->Id()." (getting $parent)\n";
    $ancestors = $parent->Genealogie();
    push @$ancestors, $self;

    # warn "Returning ".join(',',@$ancestors)."\n";
    return $ancestors;
}

=head3 Genealogie_ids : [ ids ]

Same as Genealogie, but instead of objects returns ids.

=cut
sub Genealogie_ids {
    my $self = shift;

    my @ids = ();
    my $parents = $self->Genealogie();
    @ids = map { $_->id } @$parents;
    return \@ids;
}

1;
