no warnings 'redefine';

use strict;
use RT::Attributes;

# {{{ sub Attribute

=head2 Attribute NAME

Returns the value of the attribute NAME for this object, or C<undef> if the
specified NAME does not exist.

=cut

sub Attribute {
    my ($self, $name) = @_;

    my $AttributeObj = RT::Attribute->new($self->CurrentUser);
    $AttributeObj->LoadByNameAndObject( Name => $name, Object => $self );

    return undef unless $AttributeObj->Id;
    return $AttributeObj->Description;
}

# }}}

# {{{ sub DeleteAttribute

=head2 DeleteAttribute NAME

Deletes the attribute NAME for this object.

=cut

sub DeleteAttribute {
    my ($self, $name) = @_;

    my $AttributeObj = RT::Attribute->new($self->CurrentUser);
    $AttributeObj->LoadByNameAndObject( Name => $name, Object => $self );
	
    return unless $AttributeObj->Id;
    return $AttributeObj->Delete;
}

# }}}

# {{{ sub SetAttribute

=head2 SetAttribute NAME, VALUE

Sets the value of the attribute NAME for this object.

=cut

sub SetAttribute {
    my ($self, $name, $value) = @_;

    my $AttributeObj = RT::Attribute->new($self->CurrentUser);

    $AttributeObj->LoadByNameAndObject( Name => $name, Object => $self );
    return $AttributeObj->SetDescription($value) if $AttributeObj->Id;

    return $AttributeObj->Create(
        Object      => $self,
        Name        => $name,
        Description => $value,
    );
}

# }}}


=head2 AddAttribute { Name => $name, Content => $content }

Adds a new attribute for this object.

=cut

sub AddAttribute {
    my $self = shift;
    my %args = ( Name        => undef,
                 Content     => undef,
                 @_ );

    return RT::Attribute->new( $self->CurrentUser )->Create(
        Object      => $self,
        Name        => $args{'Name'},
        Description => $args{'Content'},
    );
}

# {{{ sub Attributes

=head2 Attributes

Returns an RT::Attributes object of attributes associated with this object

=cut

sub Attributes {
    my $self = shift;

    my $Attributes = RT::Attributes->new($self->CurrentUser);
    $Attributes->LimitToObject( $self );
    return $Attributes;
}

# }}}

my ($CompanyTable, %CompanyCache);
sub CompanyName {
    my $self = shift;

    if (!$CompanyTable) {
         my $table = RT::User->table('company');
         foreach my $k (sort keys %$table) {
             my $v = $table->{$k};
             $CompanyTable->{$k} = ($v->{company_abbr} || $v->{company_code});
         }
    }

    return $CompanyTable->{$_[0]} if @_;

    my $id = ref($self) . '-' . $self->Id;
    return $CompanyCache{$id} if exists $CompanyCache{$id};
    $CompanyCache{$id} = $CompanyTable->{$self->Attribute('Company')};
}

1;
