%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2025 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 }}}
<%method new>
<%init>
return \%ARGS;
</%init>
</%method>

<%method process>

<%init>
my @actions;
$self->{SearchId} ||= $args->{'SavedChartSearchId'} || 'new';

my $SearchParams = { map { $_ => $args->{$_} } @{$self->{SearchFields}} };

my $search_id = $args->{'SavedSearchLoad'} || $args->{'SavedChartSearchId'};
if ( $search_id && $search_id ne 'new' ) {
    my $search = RT::SavedSearch->new( $session{'CurrentUser'} );
    $search->Load($search_id);
    # We have a $search and now; import the others
    $self->{SearchId} = $search_id;
    $self->{CurrentSearch}{Object} = $search;
    if ( $args->{'SavedSearchLoad'} ) {
        my $content = $search->Content;
        for ( @{ $self->{SearchFields} } ) {
            $args->{$_} = $content->{$_};
        }
    }

    $args->{SavedChartSearchId} = $args->{'SavedSearchLoad'}
        if $args->{'SavedSearchLoad'};
# saved search in /Search/Chart.html is different from /Search/Build.html
# the former is of type 'TicketChart', while the latter is of type 'Ticket'.
# After loading a saved search from the former after loading one from the
# latter, accessing /Search/Build.html will still show the old one, so we
# need to delete $session{CurrentSearchHash} to let it not show the old one.
# of course, the new one should not be shown there either because it's of
# different type
    RT::Interface::Web::Session::Delete(
        Key => 'CurrentSearchHash',
    );
}

# look for the current one in the available saved searches
if ($self->{SearchId} eq 'new') {
    my @Objects = RT::SavedSearch->new( $session{CurrentUser} )->ObjectsForLoading;

    for my $obj (@Objects) {
        for ( $m->comp( "/Search/Elements/SearchesForObject", Object => $obj ) ) {
            my ( $desc, $loc_desc, $search ) = @$_;
            use Data::Dumper;
            # FFS
            local $Data::Dumper::Sortkeys = 1;
            if ( $search->Type eq $self->{SearchType} && Dumper( $search->Content ) eq
                 Dumper( { %$SearchParams } ) ) {
                $self->{CurrentSearch}{Object}      = $search;
                $self->{SearchId}                   = $search->Id;
            }
        }
    }
}

if ( $args->{SavedSearchSave} || $args->{SavedSearchCopy} ) {
    if ( ( my $search = $self->{CurrentSearch}{Object} ) && !$args->{SavedSearchCopy} ) {
        # rename
        $search->SetName( $args->{SavedSearchName} );
        $search->SetDescription( $args->{SavedSearchDescription} );
        $search->SetDisabled( $args->{SavedSearchEnabled} ? 0 : 1 ) if $args->{SavedSearchSetEnabled};
        $search->SetContent($SearchParams);
        push @actions, loc( '[_1] [_2] updated.', loc($self->{SearchType}), $args->{SavedSearchDescription} );
    }
    else {
        # new saved search
        if ( $args->{SavedSearchCopy} && $self->{CurrentSearch}{Object} ) {
            for my $field ( qw/Name Description/ ) {
                if ( (  !$args->{"SavedSearch$field"} || $args->{"SavedSearch$field"} eq $self->{CurrentSearch}{Object}->$field ) ) {
                    $args->{"SavedSearch$field"} = loc( "[_1] copy", $self->{CurrentSearch}{Object}->$field );
                }
            }
        }

        $SearchParams->{$_} //= $defaults->{$_} for @{$self->{SearchFields}};

        my $saved_search = RT::SavedSearch->new( $session{'CurrentUser'} );
        my ( $ok, $search_msg ) = $saved_search->Create(
            PrincipalId => $args->{'SavedSearchOwner'},
            Name        => $args->{'SavedSearchName'},
            Description => $args->{'SavedSearchDescription'},
            Disabled    => $args->{'SavedSearchEnabled'} ? 0 : 1,
            Type        => $self->{'SearchType'},
            Content     => $SearchParams,
        );
        if ($ok) {
            $self->{CurrentSearch}{Object} = $saved_search;
            $self->{SearchId} = $saved_search->Id;
            push @actions, loc( '[_1] [_2] saved.', loc($self->{SearchType}), $args->{SavedSearchName} );
        } else {
            push @actions, loc("Can't save [_1]", loc($self->{SearchType})) . ': ' . loc($search_msg);
        }
    }
}

if ( $args->{SavedSearchDelete} && $self->{CurrentSearch}{Object} ) {
    my ($ok, $msg) = $self->{CurrentSearch}{Object}->Delete;
    push @actions, $ok ? loc( '[_1] [_2] deleted.', loc($self->{SearchType}), $self->{CurrentSearch}{Object}->Description ) : $msg;
    delete $self->{CurrentSearch}{Object};
    delete $self->{SearchId};
    delete $args->{SavedChartSearchId};
}

if ( $self->{CurrentSearch}{Object} ) {
    for my $field ( qw/Name Description Disabled/ ) {
        $self->{CurrentSearch}{$field} = $self->{CurrentSearch}{Object}->$field;
    }
}

return @actions;
</%init>
<%ARGS>
$self
$args
$defaults => {}
</%ARGS>

</%method>

<%method show>
<form method="post" action="<% $Action %>" name="SaveSearch">
<& /Search/Elements/EditSearches,
    Id            => $self->{SearchId} || 'new',
    Type          => $self->{SearchType},
    CurrentSearch => $self->{CurrentSearch},
    Title         => $Title,
    AllowCopy     => $AllowCopy,
    $self->{CurrentSearch}{Object} ? 
    ( Object      => $self->{CurrentSearch}{Object},
    Name          => $self->{CurrentSearch}{Object}->Name,
    Description   => $self->{CurrentSearch}{Object}->Description,
    Disabled      => $self->{CurrentSearch}{Object}->Disabled,
    ) : (),
    Class         => $Class,
&><br />
<%PERL>
foreach my $field ( @{$self->{SearchFields}} ) {
    if ( ref($ARGS{$field}) && ref($ARGS{$field}) ne 'ARRAY' ) {
        $RT::Logger->error("Couldn't store '$field'. it's reference to ". ref($ARGS{$field}) );
        next;
    }
    foreach my $value ( grep defined, ref($ARGS{$field})? @{ $ARGS{$field} } : $ARGS{$field} ) {
</%PERL>
<input type="hidden" class="hidden" name="<% $field %>" value="<% $value %>" />
%   }
% }
<input type="hidden" class="hidden" name="SavedChartSearchId" value="<% $self->{SearchId} || 'new'  %>" />
</form>
<%ARGS>
$self   => undef
$Action => ''
$Title  => loc('Saved searches')
$AllowCopy => 0
$Class => 'RT::Tickets'
</%ARGS>
<%init>
</%init>
</%method>
