%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2014 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 }}}
% if ( $ARGS{id} && $ARGS{id} ne 'new' ) {
<input type="hidden" name="<%$ARGS{'id'}%>-RefersTo" value="<% join(' ',grep {$_} sort keys %uri) %>" />
% }

<table class="articles-select-article">
% unless (RT->Config->Get('HideArticleSearchOnReplyCreate')) {
<tr>
<td><&|/l&>Search for Articles matching</&></td>
<td><input size=20 name="<% $name_prefix %>Articles_Content" /></td>
</tr>
<tr>
<td><&|/l&>Include Article:</&></td>
<td><input size=20 name="<% $name_prefix %>Articles-Include-Article-Named" /></td>
<td><input type="submit" name="Go" value="Go" /></td>
</tr>
% }
% if ($hotlist->Count) {
<tr>
<td><&|/l&>Select an Article to include</&></td>
<td><select name="<% $name_prefix %>Articles-Include-Article-Named-Hotlist" onchange="this.form.submit()">
<option value="" selected><&|/l&>-</&></option>
% while (my $article = $hotlist->Next) {
<option value="<% $article->Id %>"><%$article->Name|| loc('(no name)')%>: <%$article->Summary || ''%></option>
% }
</select>
</td>
<td><input type="submit" name="Go" value="Go" /></td>
</tr>
% }
% my %dedupe_articles;
% while (my $article = $articles_content->Next) {
%   $dedupe_articles{$article->Id}++;
<tr>
<td>&nbsp;</td>
<td><%$article->Name|| loc('(no name)')%>: <%$article->Summary%></td>
<td><input type="submit" name="<% $name_prefix %>Articles-Include-Article-<%$article->Id%>" value="Go" /></td>
</tr>
% }
% while (my $article = $articles_basics->Next) {
%   next if $dedupe_articles{$article->Id};
<tr>
<td>&nbsp;</td>
<td><%$article->Name || loc('(no name)')%>: <%$article->Summary || ''%></td>
<td><input type="submit" name="<% $name_prefix %>Articles-Include-Article-<%$article->Id%>" value="Go" /></td>
</tr>
% }
% if ( @$topics ) {
<tr>
<td>
<&|/l, $QueueObj->Name &>Choose from Topics for [_1]</&>
</td>
<td>
<select name="<% $name_prefix %>Articles-Include-Topic" onchange="this.form.submit()">
<option value="" selected>-</option>
% for ( @$topics ) { 
<option value="<% $_->{id} %>"><%'&nbsp;' x $_->{depth} . ($_->{name}|| loc('(no name)')) |n%>
</option>
% }
</select>
</td>
<td><input type="submit" name="Go" value="Go" /></td>
</tr>

% if ( $ARGS{$name_prefix .'Articles-Include-Topic'} ) {
<tr>
<td>
<&|/l, $included_topic->Name &>Select an Article from [_1]</&>
</td>
<td>
<select name="<% $name_prefix %>Articles-Include-Article" onchange="this.form.submit()">
<option value="" selected>-</option>
% while ( my $art = $topic_articles->Next ) {
<option value="<% $art->id %>"><%$art->Name||loc('(no name)')%>: <%$art->Summary%></option>
% }
</select>
</td>
<td><input type="submit" value="Go" name="Go" /></td>
</tr>

% }
% }


</table>

<%init>
my $QueueObj = $ARGS{QueueObj};
if ( $ARGS{id} && $ARGS{id} ne 'new' && !$QueueObj ) {
    my $ticket = RT::Ticket->new( $session{CurrentUser} );
    $ticket->Load( $ARGS{id} );
    $QueueObj = $ticket->QueueObj;
}

my $skip = 0;
$m->callback(CallbackName => "Init", skip => \$skip, Queue => $QueueObj);
return if $skip;

my $name_prefix = '';
if ( $ARGS{'MessageBoxName'} ) {
    $name_prefix = $ARGS{'MessageBoxName'} .'-';
}

# convert Articles-Include-Article => $id to Articles-Include-Article-$id
if ( my $tmp = $ARGS{$name_prefix ."Articles-Include-Article"} ) {
    $ARGS{$name_prefix ."Articles-Include-Article-$tmp"}++;
}

my %uri;
if ( $ARGS{id} && $ARGS{id} ne 'new' ) {
    $uri{$_}++ for split ' ', ($ARGS{$ARGS{'id'}.'-RefersTo'} || '');

    foreach my $arg (keys %ARGS) {
        next if $name_prefix && substr($arg, 0, length($name_prefix)) ne $name_prefix;

        my $article = RT::Article->new($session{'CurrentUser'});
        $article->LoadByInclude(
            Field => substr($arg, length($name_prefix)),
            Value => $ARGS{$arg},
        );
        if ($article->Id) {
            $uri{$article->URI}++;
        }
    }
}

use RT::Articles;

my $articles_content =
  RT::Articles->new( $session{'CurrentUser'} );
my $articles_basics = RT::Articles->new( $session{'CurrentUser'} );
if ( my $tmp = $ARGS{ $name_prefix ."Articles_Content" } ) {
    $articles_content->LimitCustomField(
        VALUE => $tmp, OPERATOR => 'LIKE'
    );
    $articles_content->LimitAppliedClasses( Queue => $QueueObj );

    $articles_basics->Limit( SUBCLAUSE       => 'all',
                             FIELD           => 'Name',
                             OPERATOR        => 'LIKE',
                             VALUE           => $tmp,
                             ENTRYAGGREGATOR => "OR" );
    $articles_basics->Limit( SUBCLAUSE       => 'all',
                             FIELD           => 'Summary',
                             OPERATOR        => 'LIKE',
                             VALUE           => $tmp,
                             ENTRYAGGREGATOR => "OR" );
    $articles_basics->LimitAppliedClasses( Queue => $QueueObj );
}

my $hotlist = RT::Articles->new( $session{'CurrentUser'} );
$hotlist->LimitHotlistClasses;
$hotlist->LimitAppliedClasses( Queue => $QueueObj );

my ( $topic_articles, $topics, $included_topic );
$topic_articles = RT::Articles->new( $session{CurrentUser} );
$topics = [];

my $top_topic = RT::Topic->new( $session{CurrentUser} );
$top_topic->LoadByCols( Name => 'Queues', Parent => 0 , ObjectType => 'RT::System', ObjectId => 1);

if ( $top_topic->id ) {
    my $queue_topic = RT::Topic->new( $session{CurrentUser} );
    $queue_topic->LoadByCols( Name => $QueueObj->Name, Parent => $top_topic->id );
    if ( $queue_topic->id ) {
    
        # store all topics below $queue_topic to $topics
        topics( $queue_topic, $topics, 0 );
        
        if ( my $tmp = $ARGS{ $name_prefix .'Articles-Include-Topic'}  ) {
            $included_topic = RT::Topic->new( $session{CurrentUser} );
            $included_topic->Load( $tmp );
            $topic_articles->LimitTopics( $tmp );
            $topic_articles->OrderBy( FIELD => 'Name' );
        }
    }
}


# recursively get all the topics given a top topic
sub topics {
    my $parent = shift;
    my $out = shift;
    my $depth = shift;
    while ( my $topic = $parent->Children->Next ) {
        push @$out, { id => $topic->id, name => $topic->Name, depth => $depth };
        topics( $topic, $out, $depth+1 );
    }
}

</%init>


