# $File: //depot/RT/rt/lib/RT/CustomField_Vendor.pm $ $Author: autrijus $
# $Revision: #18 $ $Change: 10595 $ $DateTime: 2004/05/12 04:33:15 $

use strict;
no warnings qw(redefine);

use vars qw(@TYPES %TYPES);

# Enumerate all valid types for this custom field
push @TYPES, (
    'FreeformDate',	# loc
    'FreeformTime',	# loc
    'FreeformNumber',	# loc
    'FreeformPassword',	# loc
    'EntrySelect',	# loc
    'EntryFreeform',	# loc
    'EntryDate',	# loc
    'EntryTime',	# loc
    'EntryNumber',	# loc
    'EntryBoolean',	# loc
    'LabelURL',		# loc
    'LabelSubject',	# loc
    'LabelAttachments',	# loc
    'LabelContent',	# loc
);

# Populate a hash of types of easier validation
for (@TYPES) { $TYPES{$_} = 1};

sub IsEntry {
    return ($_[0]->Type =~ /^Entry/);
}

sub IsSelect {
    return ($_[0]->Type =~ /Select/ or $_[0]->Type eq 'EntryExternal');
}

sub IsLabel {
    return ($_[0]->Type =~ /^Label/);
}

sub IsExternal {
    return ($_[0]->Type =~ /External/);
}

sub DescriptionOrName {
    my $self = shift;
    my $UserObj = $self->CurrentUser->UserObj;
    my $rv = '';

    if ($self->Type eq 'FreeformExternal') {
	$rv = $UserObj->describe($self->Description);
	$rv =~ s/ID$// if $rv;
    } elsif ($self->Type eq 'SelectExternal' or $self->Type eq 'EntryExternal') {
	$rv = $UserObj->field_cname($self->Description);
    } else {
	$rv = $self->Description;
    }

    $rv = $self->Name if $rv eq '';
    return $rv;
}

my %DFV_Cache;
sub DescriptionForValue {
    my $self = shift;
    my $value = shift;
    return $value unless $self->IsSelect;

    my $rv;
    if ($self->IsExternal) {
	my $UserObj = $self->CurrentUser->UserObj;
	my $sql = $UserObj->ext_table('hrms_userdefined_field')->{$self->Description}->{
	    'hrms_userdefined_field_sql'
	};
	my $SubHash = {};
	if ($sql) {
	    $sql =~ s/\$(\w+)/$UserObj->val($1)/ge;
	    $SubHash = $DFV_Cache{
		$HTML::Mason::Commands::session{_session_id},
		$UserObj->Id,
		$sql
	    } ||= $UserObj->get_hash($sql);
	}
	$rv = $SubHash->{$value};
    }
    else {
	my $cf_values = $self->Values;
	$cf_values->Limit( FIELD => 'Name', VALUE => $value );
	$rv = $cf_values->First->Description if $cf_values->Count;
    }

    $rv = $value if $rv eq '';
    return $rv;
}

sub NameToId {
    my ($self, $id, $queue) = @_;
    return $id unless $id =~ /\D/;
    my $CF = RT::CustomField->new($RT::SystemUser);
    if ($queue) {
	$CF->LoadByCols( Name => $id, Queue => RT::Queue->NameToId($queue) );
    }
    else {
	$CF->LoadByCols( Name => $id );
    }
    return $CF->Id;
}

1;
