%# BEGIN BPS TAGGED BLOCK {{{
%#
%# COPYRIGHT:
%#
%# This software is Copyright (c) 1996-2018 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 }}}
<%init>
my $default_value = {
    Query => 'id > 0',
    GroupBy => ['Status'],
    ChartStyle => 'bar+table+sql',
    ChartFunction => ['COUNT'],
};
    
$m->callback( ARGSRef => \%ARGS, CallbackName => 'Initial' );

my $title = loc( "Grouped search results");

my @search_fields = qw(Query GroupBy ChartStyle ChartFunction Width Height);
my $saved_search = $m->comp( '/Widgets/SavedSearch:new',
    SearchType   => 'Chart',
    SearchFields => [@search_fields],
);

my @actions = $m->comp( '/Widgets/SavedSearch:process',
    args     => \%ARGS,
    defaults => $default_value,
    self     => $saved_search,
);

my %query;

{
    if ($saved_search->{'CurrentSearch'}->{'Object'}) {
        foreach my $search_field (@{ $saved_search->{'SearchFields'} }) {
            $query{$search_field} = $saved_search->{'CurrentSearch'}->{'Object'}->Content->{$search_field};
        }
    }

    my $current = $session{'CurrentSearchHash'};

    my @session_fields = qw(
        Query
        SavedChartSearchId
        SavedSearchDescription
        SavedSearchLoad
        SavedSearchLoadButton
        SavedSearchOwner
    );

    for(@session_fields) {
        $query{$_} = $DECODED_ARGS->{$_} unless defined $query{$_};
        $query{$_} = $current->{$_} unless defined $query{$_};
    }

    if ($DECODED_ARGS->{'SavedSearchLoadSubmit'}) {
        $query{'SavedChartSearchId'} = $DECODED_ARGS->{'SavedSearchLoad'};
    }

    if ($DECODED_ARGS->{'SavedSearchSave'}) {
        $query{'SavedChartSearchId'} = $saved_search->{'SearchId'};
    }

}

foreach (@search_fields) {
    if ( ref $default_value->{$_} ) {
        $query{$_} = ref $ARGS{$_} ? $ARGS{$_} : [ $ARGS{$_} ];
        $query{$_} = $default_value->{$_}
            unless defined $query{$_} && defined $query{$_}[0];
    }
    else {
        $query{$_} = ref $ARGS{$_} ? $ARGS{$_} : $ARGS{$_};
        $query{$_} = $default_value->{$_}
            unless defined $query{$_};
    }
}

$m->callback( ARGSRef => \%ARGS, QueryArgsRef => \%query );

</%init>
<& /Elements/Header, Title => $title &>
<& /Elements/Tabs, QueryArgs => \%query &>
<& /Elements/ListActions, actions => \@actions &>

% $m->callback( ARGSRef => \%ARGS, CallbackName => 'BeforeChart' );

<& /Search/Elements/Chart, %ARGS &>

% $m->callback( ARGSRef => \%ARGS, CallbackName => 'AfterChart' );

<div class="chart-meta">
<div class="chart-type">

<form method="get" action="<% RT->Config->Get('WebPath') %>/Search/Chart.html">
<input type="hidden" class="hidden" name="Query" value="<% $query{Query} %>" />
<input type="hidden" class="hidden" name="SavedChartSearchId" value="<% $saved_search->{SearchId} || 'new' %>" />

<&| /Widgets/TitleBox, title => loc('Group by'), class => "chart-group-by" &>
<fieldset><legend><% loc('Group tickets by') %></legend>
<& Elements/SelectGroupBy,
    Name => 'GroupBy',
    Query => $query{Query},
    Default => $query{'GroupBy'}[0],
    &>
</fieldset>
<fieldset><legend><% loc('and then') %></legend>
<& Elements/SelectGroupBy,
    Name => 'GroupBy',
    Query => $query{Query},
    Default => $query{'GroupBy'}[1] // q{},
    ShowEmpty => 1,
    &>
</fieldset>
<fieldset><legend><% loc('and then') %></legend>
<& Elements/SelectGroupBy,
    Name => 'GroupBy',
    Query => $query{Query},
    Default => $query{'GroupBy'}[2] // q{},
    ShowEmpty => 1,
    &>
</fieldset>
</&>

<&| /Widgets/TitleBox, title => loc("Calculate"), class => "chart-calculate" &>

<fieldset><legend><% loc('Calculate values of') %></legend>
<& Elements/SelectChartFunction, Default => $query{'ChartFunction'}[0] &>
</fieldset>
<fieldset><legend><% loc('and then') %></legend>
<& Elements/SelectChartFunction, Default => $query{'ChartFunction'}[1] // q{}, ShowEmpty => 1 &>
</fieldset>
<fieldset><legend><% loc('and then') %></legend>
<& Elements/SelectChartFunction, Default => $query{'ChartFunction'}[2] // q{}, ShowEmpty => 1 &>
</fieldset>

</&>

<&| /Widgets/TitleBox, title => loc('Picture'), class => "chart-picture" &>
<input name="ChartStyle" type="hidden" value="<% $query{ChartStyle} %>" />
<label><% loc('Style') %>: <& Elements/SelectChartType, Default => $query{ChartStyle} =~ /^(pie|bar|table)\b/ ? $1 : undef &></label>
<span class="width">
<label><% loc("Width") %>: <input type="text" name="Width" value="<% $query{'Width'} || q{} %>"> <% loc("px") %></label>
</span>
<span class="height">
  &#x00d7;
  <label><% loc("Height") %>: <input type="text" name="Height" value="<% $query{'Height'} || q{} %>"> <% loc("px") %></label>
</span>
<div class="include-table">
    <input type="checkbox" name="ChartStyleIncludeTable" <% $query{ChartStyle} =~ /\btable\b/ ? 'checked="checked"' : '' |n %>> <% loc('Include data table') %>
</div>
<div class="include-sql">
    <input type="checkbox" name="ChartStyleIncludeSQL" <% $query{ChartStyle} =~ /\bsql\b/ ? 'checked="checked"' : '' |n %>> <% loc('Include TicketSQL query') %>
</div>
</&>
<script type="text/javascript">
var updateChartStyle = function() {
    var val = jQuery(".chart-picture [name=ChartType]").val();
    if ( val != 'table' && jQuery(".chart-picture [name=ChartStyleIncludeTable]").is(':checked') ) {
        val += '+table';
    }
    if ( jQuery(".chart-picture [name=ChartStyleIncludeSQL]").is(':checked') ) {
        val += '+sql';
    }
    jQuery(".chart-picture [name=ChartStyle]").val(val);
};
jQuery(".chart-picture [name=ChartType]").change(function(){
    var t = jQuery(this);
    t.closest("form").find("[name=Height]").closest(".height").toggle( t.val() == 'bar' );
    t.closest("form").find("[name=Width]").closest(".width").toggle( t.val() !== 'table' );
    t.closest("form .chart-picture").find("div.include-table").toggle( t.val() !== 'table' );
    updateChartStyle();
}).change();

jQuery(".chart-picture [name=ChartStyleIncludeTable]").change( updateChartStyle );
jQuery(".chart-picture [name=ChartStyleIncludeSQL]").change( updateChartStyle );
</script>

<& /Elements/Submit, Label => loc('Update Chart'), Name => 'Update' &>
</form>

</div>
<div class="saved-search">
    <& /Widgets/SavedSearch:show, %ARGS, Action => 'Chart.html', self => $saved_search, Title => loc('Saved charts') &>
</div>
</div>
