%# BEGIN LICENSE BLOCK
%# 
%# Copyright (c) 1996-2009 Jesse Vincent <jesse@bestpractical.com>
%# 
%# (Except where explictly superceded by other copyright notices)
%# 
%# This work is made available to you under the terms of Version 2 of
%# the GNU General Public License. A copy of that license should have
%# been provided with this software, but in any event can be snarfed
%# from www.gnu.org
%# 
%# This work is distributed in the hope that it will be useful, but
%# WITHOUT ANY WARRANTY; without even the implied warranty of
%# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
%# General Public License for more details.
%# 
%# 
%# Unless otherwise specified, all modifications, corrections or
%# extensions to this work which alter its source code become the
%# property of Best Practical Solutions, LLC when submitted for
%# inclusion in the work.
%# 
%# 
%# END LICENSE BLOCK
<& /Ticket/Elements/EditCustomFields, 
  TicketObj => $TicketObj, 
  QueueObj => $QueueObj,
  %ARGS,
  InTable => 1,
&>

<%INIT>
unless ( $TicketObj && $TicketObj->Id ) {
    # no ticket, we need to find defaults of cfs
    my $CustomFields = $QueueObj->TicketCustomFields();
    my %Defaults = RT->Config->Get('RTIR_CustomFieldsDefaults');
    while ( my $CustomField = $CustomFields->Next ) {
        my $name = $CustomField->Name;

        if ( $DefaultsFrom ) {
            my ($link_cf) = RT::IR->CustomFields( Field => $name, Ticket => $DefaultsFrom );
            if ( $link_cf ) {
# XXX: if CF can have only one value then we should use only first value
                $ARGS{"CustomField-".$CustomField->Id} = join "\n",
                    grep defined && length, map $_->Content,
                    @{ $DefaultsFrom->CustomFieldValues( $link_cf->id )->ItemsArrayRef };
                next;
            }
        }
        
        if ( $ARGS{"$name-Value"} ) {
            $ARGS{"CustomField-".$CustomField->Id} = $ARGS{"$name-Value"};
        }
        elsif ( defined $Defaults{ $name } ) {
# if $Defaults{$name} is ref, it should be treated carefully
            unless ( ref $Defaults{ $name } ) {
                $ARGS{"CustomField-".$CustomField->Id} = $Defaults{ $name };
            }
            elsif ( ref $Defaults{ $name } eq 'ARRAY' ) {
                $ARGS{"CustomField-".$CustomField->id} =
                    join "\n", @{$Defaults{ $name }};
            }
        }
    }
}

</%INIT>
<%ARGS>
$TicketObj => undef
$QueueObj => undef
$DefaultsFrom => undef
</%ARGS>
