%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2016 Best Practical Solutions, LLC
%#                                          <sales@bestpractical.com>
%#
%# (Except where explicitly superseded by other copyright notices)
%#
%#
%# LICENSE:
%#
%# 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.
%#
%# You should have received a copy of the GNU General Public License
%# along with this program; if not, write to the Free Software
%# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
%# 02110-1301 or visit their web page on the internet at
%# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
%#
%#
%# CONTRIBUTION SUBMISSION POLICY:
%#
%# (The following paragraph is not intended to limit the rights granted
%# to you to modify and distribute this software under the terms of
%# the GNU General Public License and is only of importance to you if
%# you choose to contribute your changes and enhancements to the
%# community by submitting them to Best Practical Solutions, LLC.)
%#
%# By intentionally submitting any modifications, corrections or
%# derivatives to this work, or any other work intended for use with
%# Request Tracker, to Best Practical Solutions, LLC, you confirm that
%# you are the copyright holder for those contributions and you grant
%# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
%# royalty-free, perpetual, license to use, copy, create derivative
%# works based on those contributions, and sublicense and distribute
%# those contributions and any derivatives thereof.
%#
%# END BPS TAGGED BLOCK }}}
<%args>
$Ticket
$ShowRelatedTickets => 10
</%args>
<%init>
my $target_assets = $Ticket->Links("Base")->Clone;
$target_assets->Limit(
    FIELD    => "Target",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);
my $base_assets = $Ticket->Links("Target")->Clone;
$base_assets->Limit(
    FIELD    => "Base",
    OPERATOR => "STARTSWITH",
    VALUE    => RT::URI::asset->LocalURIPrefix,
);

my @linked_assets;
push @linked_assets, grep { defined } map { $_->TargetURI->IsLocal }
    @{ $target_assets->ItemsArrayRef };
push @linked_assets, grep { defined } map { $_->BaseURI->IsLocal }
    @{ $base_assets->ItemsArrayRef };

my $asset_queue;
if (RT->Config->Get('AssetQueues')) {
    $asset_queue = 1 if grep {$_ eq $Ticket->QueueObj->Name} @{RT->Config->Get('AssetQueues')}
} else {
    $asset_queue = 0;
}
return unless @linked_assets or ($Ticket->CurrentUserHasRight("ModifyTicket")
                                     and $asset_queue);

my $assets = RT::Assets->new( $session{CurrentUser} );
$assets->OrderBy( FIELD => "Name", ORDER => "ASC" );
if ( @linked_assets ) {
    $assets->Limit(
        FIELD       => "id",
        OPERATOR    => "IN",
        VALUE       => \@linked_assets,
    );
}

my $Format = RT->Config->Get("AssetSummaryFormat") || q[
    '<a href="__WebHomePath__/Asset/Display.html?id=__id__">__Name__</a>/TITLE:Name',
    Description,
    Status,
    Catalog,
];

$m->callback(
    CallbackName    => 'ModifyCollection',
    Ticket          => $Ticket,
    Assets          => $assets,
    Format          => \$Format,
);


</%init>
<&| /Widgets/TitleBox,
    title => loc('Assets'),
    class => 'ticket-assets',
    title_class => "inverse",
    &>

<form action="<% RT->Config->Get("WebPath") %>/Ticket/Display.html" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="id" value="<% $Ticket->id %>">

% $m->callback( CallbackName => "Start", Ticket => $Ticket, Assets => $assets );

<div id="assets-accordion" class="rt-accordion">
% my $display_path = $session{'CurrentUser'}->Privileged ? 'Asset' : 'SelfService/Asset';
% while (my $asset = $assets->Next) {
  <h3><a href="<% RT->Config->Get('WebPath') %>/<% $display_path %>/Display.html?id=<% $asset->id %>"><&|/l, $asset->id, $asset->Name &>#[_1]: [_2]</&></a>
<%perl>
if ($Ticket->CurrentUserHasRight("ModifyTicket")) {
    my $targets = $asset->Links("Target")->Clone;
    $targets->Limit(
        FIELD   => "LocalBase",
        VALUE   => $Ticket->id,
    );
    my $bases = $asset->Links("Base")->Clone;
    $bases->Limit(
        FIELD   => "LocalTarget",
        VALUE   => $Ticket->id,
    );

    my %params;
    $params{join("-", "DeleteLink", "", $_->Type, $_->Target)} = 1
        for @{ $targets->ItemsArrayRef };
    $params{join("-", "DeleteLink", $_->Base, $_->Type, "")} = 1
        for @{ $bases->ItemsArrayRef };

    my $delete_url = RT->Config->Get("WebPath")
        . "/Ticket/Display.html?"
        . $m->comp("/Elements/QueryString", id => $Ticket->id, %params);
</%perl>
<a href="<% $delete_url %>" class="unlink-asset ui-icon ui-icon-circle-close" title="Unlink asset">X</a>
% }
  </h3>
  <div class="details">
    <& /Elements/ShowRecord,
        Object      => $asset,
        Format      => $Format,
        TrustFormat => 1,
        &>
% $m->callback( CallbackName => "BeforeTickets", Ticket => $Ticket, Asset => $asset );
<%perl>
if ($ShowRelatedTickets) {
    my %search = (
        Query   => "id != '@{[$Ticket->id]}' AND LinkedTo = 'asset:@{[$asset->id]}'",
        OrderBy => "LastUpdated",
        Order   => "DESC",
    );
    my $url = RT->Config->Get("WebPath")
            . "/Search/Results.html?"
            . $m->comp("/Elements/QueryString", %search);
</%perl>
    <div class="related-tickets">
      <span class="label">
        <a href="<% $url %>">
          <&|/l, $ShowRelatedTickets &>[_1] most recently updated related tickets</&>
        </a>
      </span>
      <& /Elements/CollectionList,
          %search,
          Class             => "RT::Tickets",
          Format            => RT->Config->Get("AssetSummaryRelatedTicketsFormat"),
          Rows              => $ShowRelatedTickets,
          ShowHeader        => 0,
          AllowSorting      => 0,
          ShowNavigation    => 0,
      &>
    </div>
% }

% $m->callback( CallbackName => "PerAsset", Ticket => $Ticket, Asset => $asset );

  </div>
% }
</div>

% if ($Ticket->CurrentUserHasRight("ModifyTicket")) {
  <div class="add-asset">
    <label>
      <&|/l&>Add an asset to this ticket</&>
    <input size="10" name="<% $Ticket->id %>-RefersTo" placeholder="<&|/l&>Asset #</&>" type="text">
    </label>
    <input type="submit" value="+">
  </div>
% }

% $m->callback( CallbackName => "End", Ticket => $Ticket, Assets => $assets );

</form>

</&>
