<%! import urllib
title = 'Triggered Alerts'
from splunk.appserver.mrsparkle.lib import util
isLite = util.isLite()
%>
<%inherit file="/layout/base.html"/>
<%namespace name="lib" file="/lib.html" import="stylesheet_tags, add_script_block, csrf_hidden_input, sort_link, get_application_css, generate_splunk_header" />

<%def name="css()">
<%coreCSSFiles = [
'/static/css/view.css',
'/static/css/alerts.css',
'/static/css/skins/default/default.css',
'/static/css/print.css',
] %>
<%
    if isLite:
        coreCSSFiles.append('/static/build/css/splunk-components-lite.css')
    else:
	    coreCSSFiles.append('/static/build/css/splunk-components-enterprise.css')
    endif
%>
<%lib:stylesheet_tags files="${coreCSSFiles}" />
</%def>
<%def name="js()">
${lib.script_tags(files=[
    "/static/build/modules_nav/lite/index.js" if isLite else "/static/build/modules_nav/enterprise/index.js"
])}
    <script type="text/javascript">
    //<![CDATA[

        $(window).bind('load resize', function() {
            // At page load, the footer is not rendered yet when this executes, put a default 55px which is equivalent to
            // $(".splunk-components").outerHeight() + parseInt($('.nav-footer').css('margin-bottom'), 10)
            var pageHeight = $(window).height(),
                $results = $("#results"),
                $pagination = $("#Pagination"),
                paginationHeight = $pagination ? $pagination.outerHeight() : 0,
                footerOffsetHeight = $(".splunk-components").outerHeight() + parseInt($('.nav-footer').css('margin-bottom'), 10) || 55,
                headerHeight = $("#header").outerHeight(),
                filtersHeight = $("#filters").outerHeight(),
                actionsHeight = $("#actions").outerHeight(),
                targetHeight = pageHeight - headerHeight - filtersHeight - paginationHeight - actionsHeight - footerOffsetHeight;
            // reset the previous calculated height if any
            $results.css('height', "auto");
            if ($results.outerHeight() > targetHeight) {
                $results.css('height', targetHeight + "px");
            }
        });
        $("#actions .all").click(function() {
            $("#results input").attr("checked", true);
            return false;
        });
        $("#actions .none").click(function() {
            $("#results input").attr("checked", false);
            return false;
        });
        $("#filters select").change(function() {
            var search = window.location.search;
            var query1 = (search) ? Splunk.util.queryStringToProp(search) : {};
            var query2 = {};
            $("#filters select").each(function() {
                query2[this.name] = encodeURIComponent($(this).val());
            });
            
            // reset to page 1 when applying a filter
            query2['offset'] = 0;
            
            $.extend(query1, query2);
            // we don't want to propage alerts_id if one of the other selects has changed
            if(this.name != "alerts_id"){
                delete query1.alerts_id;
            }
            window.location.search = Splunk.util.propToQueryString(query1);
        });
    //]]>
    </script>
    <%lib:generate_splunk_header />
</%def>

<%def name="body_element_open()">
	% if isLite:
	    <body id="alerts" class="alerts-page lite">
	% else:
		<body id="alerts" class="alerts-page">
	% endif
</%def>

<div class="appHeaderWrapper" id="header">
    <div class="layoutRow oneColRow splClearfix appHeader">
        <div class="SplunkModule AccountBar">

        </div>
    </div>
</div>

<div class="alerts-page-wrapper">
<div id="filters" class="alerts-section-filters">
    <%
    if cherrypy.request.params.has_key('offset') and cherrypy.request.params['offset'] >= fired_alerts.get_total() and not pager.next_exists():
        cherrypy.request.params['offset'] = pager.previous_offset()
    %>
    <form action="${ make_url(['alerts', app], _qs=cherrypy.request.params) }" method="get">
        <table>
            <tr>
                <td class="col1">
                    <ul class="splClearfix">
                        <li>
                            <label for="app">${_('App')}</label>
                            <select name="eai:acl.app" id="app">
                                <option value="*"${' selected="selected"' if '*'==cherrypy.request.params.get('eai:acl.app') else ''}>${_('All')}</option>
                                % for apps_item in apps:
                                    <option value="${apps_item.name|h}"${' selected="selected"' if apps_item.name==cherrypy.request.params.get('eai:acl.app') or apps_item.name == app else ''}>${apps_item.label|h} (${apps_item.name|h})</option>
                                % endfor
                            </select>
                        </li>
                        <li>
                            <label for="owner">${_('Owner')}</label>
                            <select name="eai:acl.owner" id="owner">
                                <option value="*"${' selected="selected"' if '*'==cherrypy.request.params.get('eai:acl.owner') else ''}>${_('All')}</option>
                                % for owner_item in users:
                                    <option value="${owner_item.name|h}"${' selected="selected"' if owner_item.name==urllib.unquote_plus(cherrypy.request.params.get('eai:acl.owner', current_user)) else ''}>${owner_item.realname or owner_item.name|h} (${owner_item.name|h})</option>
                                % endfor
                            </select>
                        </li>
                        <li>
                            <label for="severity">${_('Severity')}</label>
                            <select name="severity" id="severity">
                                <% severities = ('1', _('Info')), ('2', _('Low')), ('3', _('Medium')), ('4', _('High')), ('5', _('Critical')) %>
                                <option value="*"${' selected="selected"' if '*'==cherrypy.request.params.get('severity') else ''}>${_('All')}</option>
                                % for severity in severities:
                                    <option value="${severity[0]|h}"${' selected="selected"' if severity[0]==cherrypy.request.params.get('severity') else ''}>${severity[1]|h}</option>
                                % endfor
                            </select>
                        </li>
                        <li>
                            <label for="alerts_id">${_('Alert')}</label>
                            <select name="alerts_id" id="alerts_id">
                                % for fired_alert_summary_info in fired_alert_summary:
                                        <% is_checked = fired_alert_summary_info.id==urllib.unquote_plus(cherrypy.request.params.get('alerts_id', '')) %>
                                    % if fired_alert_summary_info.name is not '-':
                                        <option value="${fired_alert_summary_info.id|h}"${' selected="selected"' if is_checked else ''}>${fired_alert_summary_info.name|h}</option>
                                    % else:
                                         <option value="${fired_alert_summary_info.id|h}"${' selected="selected"' if is_checked else ''}>${_('All')}</option>
                                    % endif
                                % endfor
                            </select>
                        </li>
                    </ul>
                </td>
                <td class="col2">
                    <input name="search" id="search" class="formelement1" type="text" paceholder="Filter" value="${cherrypy.request.params.get('search', '')|h}"/>
                    &nbsp;
                    <input type="submit" class="searchButton" value=""/>
                </td>
            </tr>
        </table>
    </form>
</div>

% if fired_alerts.get_total()>0:
<div id="Pagination" class="splClearfix">
    <ul class="splClearfix">
        <%
        qs = {}
        qs.update(cherrypy.request.params)
        %>
        % if pager.previous_exists():
            <% qs['offset'] = pager.previous_offset() %>
            <li>
                <a href="${ make_url(['alerts', app], _qs=qs) }" class="previous">&laquo;${_('prev')}</a>
            </li>
        % else:
            <li>
                <a href="#" class="disabled" onclick="return false;">&laquo;${_('prev')}</a>
            </li>
        % endif

        % for page in pager.page_range:
            <% qs['offset'] = pager.page_item_offset(page) %>
            <li>
                <a href="${ make_url(['alerts', app], _qs=qs) }" class="${'active' if pager.is_active_page(page) else ''}">${page|h}</a>
            </li>
        % endfor

        % if pager.next_exists():
            <% qs['offset'] = pager.next_offset() %>
            <li>
                <a href="${ make_url(['alerts', app], _qs=qs) }">${_('next')}&raquo;</a>
            </li>
        % else:
            <li>
                <a href="#" class="disabled" onclick="return false;">${_('next')}&raquo;</a>
            </li>
        % endif
    </ul>
    <p class="count">${ungettext('Showing <span>%(first)s-%(last)s</span> of %(total)s result', 'Showing <span>%(first)s-%(last)s</span> of %(total)s results', pager.item_count) % dict(first=offset+1, last=min(pager.item_count,offset+count), total=pager.item_count)}</p>
</div>
% endif

<div id="results" class="alerts-section-results">
    <form action="${ make_url(['alerts', app, 'delete'], _qs=cherrypy.request.params) }" method="post" id="bulk">
        ${csrf_hidden_input()}
        <table>
            % if fired_alerts.get_total()>0:
                <thead>
                    <tr>
                        <th class="bulk">Bulk Action</th>
                        <th>${sort_link(_('Time'), ['alerts', app], cherrypy.request.params, 'trigger_time')}</th>
                        <th>${sort_link(_('Fired alerts'), ['alerts', app], cherrypy.request.params, 'alerts_id')} </th>
                        <th>${_('App')}</th>
                        <th>${sort_link(_('Type'), ['alerts', app], cherrypy.request.params, 'alert_type')}</th>
                        <th>${sort_link(_('Severity'), ['alerts', app], cherrypy.request.params, 'severity')}</th>
                        <th>${sort_link(_('Mode'), ['alerts', app], cherrypy.request.params, 'digest_mode')}</th>
                        <th><span>${_('Actions')}</span></th>
                    </tr>
                </thead>
                <tbody>
                    % for fired_alert in fired_alerts[offset:offset+count]:
                        <tr>
                            <td><input type="checkbox" name="id" value="${fired_alert.id|h}" /></td>
                            <td>${fired_alert.trigger_time_rendered|h}</td>
                            <td>${fired_alert.savedsearch_name|h}</td>
                            <td>${fired_alert.namespace|h}</td>
                            <td>${_('Real-time') if fired_alert.alert_type=='real time' else _('Scheduled')}</td>
                            <td>
                                <% severity_list = [('info', _('Info')), ('low', _('Low')), ('medium', _('Medium')), ('high', _('High')), ('critical', _('Critical'))] %>
                                <span class="severity severity${severity_list[fired_alert.severity-1][0]|h}">${severity_list[fired_alert.severity-1][1]|h}</span>
                            </td>
                                                        <td>
                                                            % if fired_alert.digest_mode:
                                                                  Digest
                                                            % else:
                                                                  Per Result
                                                            % endif
                                                        </td>
                            <td>
                                    <a href="${make_url(['app', fired_alert.namespace, '@go'], _qs=dict(sid=fired_alert.sid))}" target="_blank" class="spl-icon-external-link-xsm">
                                    <span>${_('View results')}</span>
                                </a>
                                <span class="splPipe">|</span>
                                % if isLite:
                                    <a href="${make_url(['app', fired_alert.namespace, 'alert'], _qs=dict(s=fired_alert.entity.getLink('savedsearch')))}" target="_blank" class="spl-icon-external-link-xsm">
                                        <span>${_('Open alert')}</span>
                                    </a>
                                % else:
                                    <% search = '"' + fired_alert.savedsearch_name + '"' %>
                                    <a href="${make_url(['manager', fired_alert.namespace, 'saved', 'searches', fired_alert.name], _qs=dict(app=fired_alert.namespace, owner=fired_alert.owner, search=search, uri=fired_alert.entity.getLink('savedsearch'), action='edit'))|h}" target="_blank" class="spl-icon-external-link-xsm">
                                        <span>${_('Edit search')}</span>
                                    </a>
                                % endif
                                <span class="splPipe">|</span>
                                <a href="#"  onclick="$('form').find(':checkbox').prop('checked', false); $(this).closest('tr').find('input[type=\'checkbox\']')[0].checked=true; $('#bulk').submit(); return false;">
                                    <span>${_('Delete')}</span>
                                </a>
                            </td>
                        </tr>
                    % endfor
                </tbody>
            % else:
                <tr>
                    <td class="none empty_results">
                        ${_('No triggered alerts found. <a href="%(url)s">Reload</a>.') % dict(url=make_url(['alerts', app], _qs=cherrypy.request.params))}
                    </td>
                </tr>
            % endif
        </table>
    </form>
</div>
<div id="actions" class="alerts-section-actions">
    % if fired_alerts.get_total()>0:
        <div id="actionsSelection">
            <span>${_('Select')}</span>
            <a href="#" class="all">All</a>
            <span>|</span>
            <a href="#" class="none">None</a>
            <span class="selected">${_('Selected alerts')}</span>
            <button class="splButton-secondary" type="button" onclick="$('#bulk').submit();">
                <span>${_('Delete')}</span>
            </button>
        </div>
    % endif
</div>
</div><!-- /.alerts-page-wrapper -->
