%# RT::Extension::ReferenceIDoitObjects
%#
%# Copyright 2011-12 synetics GmbH, http://i-doit.org/
%#
%# This program is free software; you can redistribute it and/or modify it under
%# the same terms as Perl itself.
%#
%# Request Tracker (RT) is Copyright Best Practical Solutions, LLC.

<& /Elements/Header, Title => loc('Modify referenced i-doit objects for ticket #[_1]', $TicketObj->Id) &>
<& /Elements/Tabs &>

% $m->callback(CallbackName => 'BeforeActionList', Actions => \@results, ARGSRef => \%ARGS, Ticket => $TicketObj);

<& /Elements/ListActions, actions => \@results &>

<form name="ModifyReferencedIDoitObjects" method="post" action="ModifyIDoitObjects.html?id=<% $TicketObj->Id %>">
    <input type="hidden" class="hidden" name="id" value="<% $TicketObj->Id %>" />
    <input type="hidden" id="Requestors" name="Requestory" value="<% $TicketObj->RequestorAddresses %>" />
    <input type="hidden" id="Subject" name="Subject" value="<% $TicketObj->Subject %>" />
    <&| /Widgets/TitleBox, title => loc('These fields are needed to modify referenced i-doit objects.'), class=>'ticket-info-basics' &>
        <& Elements/EditCustomFields, TicketObj => $TicketObj &>
    </&>
    <br />
    <&| /Widgets/TitleBox,title => loc('Modify referenced i-doit objects for ticket #[_1]', $TicketObj->Id), class=> 'ticket-info-basic' &>
        <& Elements/EditIDoitObjects, TicketObj => $TicketObj &>
    </&>
    <& /Elements/Submit, Name => 'SubmitTicket', Label => loc('Save Changes') &>  
</form>

<script type="text/javascript">
    (function($) {
        $('form[name="ModifyReferencedIDoitObjects"]').submit(function() {
            window.log_changed_objects(true);
            return true;
        });
    })(jQuery);
</script>

<%INIT>
my @results;
my $TicketObj = LoadTicket($id);
$m->callback( TicketObj => $TicketObj, ARGSRef => \%ARGS );
push @results, ProcessObjectCustomFieldUpdates(Object => $TicketObj, ARGSRef => \%ARGS);
$TicketObj->ApplyTransactionBatch;

## Set default mandator if necessary:
my $cfMandator = 'i-doit mandator';
my $IDoitMandator = $TicketObj->FirstCustomFieldValue($cfMandator);
unless ($IDoitMandator) {
    $IDoitMandator = RT->Config->Get('IDoitDefaultMandator');

    unless ($IDoitMandator) {
        my $msg = loc('Default mandator is not configured.');
        RT::Logger->error($msg);
        $$skip_create = 1;
        push @{$results}, $msg;
    }

    my $cf = RT::CustomField->new($RT::SystemUser);
    $cf->LoadByNameAndQueue(Name => $cfMandator, Queue => $TicketObj->Queue);
    unless ($cf->id) {
        $cf->LoadByNameAndQueue(Name => $cfMandator, Queue => 0);
    }

    my ($val, $msg) = $TicketObj->AddCustomFieldValue(Field => $cf, Value => $IDoitMandator);
    unless ($val) {
        $RT::Logger->error('Could not set default mandator: ' . $msg);
        return 0;
    }
}
</%INIT>

<%ARGS>
$id => undef
$skip_create => undef
$results => undef
</%ARGS>
