<%inherit file="/layout/wizard.html"/>
<%namespace file="/lib.html" import="csrf_hidden_input, wizard_cancel_delete, wizard_errors, wizard_schedules"/>
<%
    def is_selected(model_value, option_value, none_value=None):
        if model_value is None and option_value == none_value:
            return True
        if model_value == option_value:
            return True
        return False
%>
<div class="content alertStep2">
    <%include file="_steps.html" args="step=2"/>
    <form method="post" action="${make_url(['alertswizard', app, 'step2', 'update']) | h}">
        ${wizard_errors(header=_('Your alert settings could not be saved.'), errors=saved_search.errors)}
        ${csrf_hidden_input()}
        <input type="hidden" name="id" value="${saved_search.id | h}"/>
        <table>
            <tbody>
                <tr>
                    <td class="col1"><label for="condition">${_('Condition')}</label></td>
                    <td class="col2">
                        <select name="alert.type" id="condition" class="width_medium">
                            % if not saved_search.is_realtime():
                                <option value="always"${' selected="selected"' if saved_search.alert.type=="always" else ''}>${_('Always')}</option>
                            % endif
                            <option value="number of events" class="numericConditionState"${' selected="selected"' if saved_search.alert.type=="number of events" else ''}>${_('If number of events')}</option>
                            <option value="number of hosts" class="numericConditionState"${' selected="selected"' if saved_search.alert.type=="number of hosts" else ''}>${_('If number of hosts')}</option>
                            <option value="number of sources" class="numericConditionState"${' selected="selected"' if saved_search.alert.type=="number of sources" else ''}>${_('If number of sources')}</option>
                            <option value="custom" class="customConditionState"${' selected="selected"' if saved_search.alert.type is None else ''}>${_('If custom condition is met')}</option>
                        </select>
                        <div class="indent numericCondition">
                            <select name="alert.comparator" class="width_short">
                                <% 
                                    options = [('greater than', _('is greater than')), ('less than', _('is less than')), ('equal to', _('is equal to'))]
                                    if not saved_search.is_realtime():
                                        options = options + [('drops by', _('drops by')), ('rises by', _('rises by'))]
                                %>
                                % for option in options:
                                    <option value="${option[0] | h}"${' selected="selected"' if saved_search.alert.comparator==option[0] else ''}>${option[1] | h}</option>
                                % endfor
                            </select>
                            <input name="alert.threshold" type="text" value="${saved_search.alert.threshold or '0' | h}"/>
                        </div>
                        <div class="indent customCondition">
                            <ul>
                                <li>
                                    <input name="alert.condition" id="alert_condition" type="text" value="${saved_search.alert.condition or '' | h}" id="conditional_search" placeholder="${_('Conditional search string')}" />
                                </li>
                                <li class="note">
                                    <em>${_('This conditional search is evaluated against the results of the base search.')}</em>
                                    <a href="${generateSelfHelpLink('learnmore.alert.conditionalsrch')}" class="spl-icon-external-link-xsm" target="_blank">${_('Learn more')}</a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
                % if not saved_search.is_realtime():
                    <tr>
                        <td class="col1"><label for="alert_preset">${_('Schedule')}</label></td>
                        <td class="col2 alertSchedule">
                            <p>
                                <select name="alert_preset" id="alert_preset" class="width_medium">
                                    <optgroup label="${_('Every')}">
                                    <% has_selected = False %>
                                    % for option in wizard_schedules():
                                        <% 
                                        if is_selected(saved_search.schedule.cron_schedule, option[0], none_value='0 */12 * * *'):
                                            has_selected = True
                                        %>
                                        <option value="${option[0] | h}"${' selected="selected"' if is_selected(saved_search.schedule.cron_schedule, option[0], none_value='0 0 * * *') else ''}>${option[1] | h}</option>
                                    % endfor
                                    </optgroup>
                                    <option value="cron"${'' if has_selected else ' selected="selected"'}>${_('Custom')}</option>
                                </select>	
                            </p>
                            <div class="indent" id="alert_cron">
                                <ul>
                                    <li>
                                        <input type="text" id="alert_cron_tmp" name="alert_cron" class="width_medium" value="${'' if has_selected else saved_search.schedule.cron_schedule | h}" id="alert_schedule_cron_value" placeholder="${_('Cron schedule')}" />
                                    </li>
                                    <li class="note">
                                        <em>${_('ex: */5 * * * * (every 5 minutes)<br>ex: 0 21 * * * (every day at 9 PM)')}</em>
                                    </li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                % else :
                    <input type="hidden" name="alert_preset" value="* * * * *" />
                % endif
                <tr>
                    <td class="col1"><label for="alert_mode">${_('Alert Mode')}</label></td>
                    <td class="col2">
                        <select name="alert.digest_mode" id="digest_mode" class="width_medium">
                            <option value="1" class="numericConditionState"${' selected="selected"' if saved_search.alert.digest_mode=="1" else ''}>${_('Once per search')}</option>
                            <option value="0" class="numericConditionState"${' selected="selected"' if saved_search.alert.digest_mode=="0" else ''}>${_('Once per result')}</option>
                        </select>
                        <p class="note" style="padding-top:5px;">
                            ${_('<a href="%s" class="spl-icon-external-link-xsm" target="_blank">Learn more</a> about alert mode.') % generateSelfHelpLink('learnmore.alert.mode')}
                        </p>
                    </td>
                </tr>
                <tr>
                    <td class="col1"><label for="suppress_toggle">${_('Throttling')}</label></td>
                    <td class="col2 suppression">
                        <input type="checkbox" class="typeCheckbox" name="saved_search.alert.suppress.enabled" value="1" id="suppress_toggle"${' checked="checked"' if saved_search.alert.suppress.enabled else '' | h}/>
                        <label for="suppress_toggle">${_("After triggering the alert, don't trigger it again for")}</label>
                        <div class="indent">
                            <input type="text" name="suppress_value" class="suppressValue" value="${saved_search.time_value(saved_search.alert.suppress.period) or '' | h}">
                            <select name="suppress_unit"  class="width_short">
                                <% 
                                   options   = [('s', _('second(s)')), ('m', _('minute(s)')), ('h', _('hour(s)')), ('d', _('day(s)'))]
                                   time_unit = saved_search.time_unit(saved_search.alert.suppress.period)
                                   time_unit = 'h' if time_unit == None else time_unit
                                 %>
                                % for option in options:
                                    <option value="${option[0] | h}"${' selected="selected"' if option[0]==time_unit else ''}>${option[1] | h}</option>
                                % endfor
                            </select>
                            <div id="suppressfields">
                                <label for="suppress_fields">${_('for results with the same')}</label><br>
                                <input type="text" name="alert.suppress.fields" class="width_medium" placeholder="${_('Comma separated fields')}">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td class="col1"><label for="expiration">${_('Expiration')}</label></td>
                    <td class="col2 alertExpiration">
                        <% options = [('6h', _('After 6 hours')), ('12h', _('After 12 hours')), ('24h', _('After 24 hours')), ('2d', _('After 2 days')), ('7d', _('After 7 days'))] %>
                        <select name="alert.expires" id="expiration"  class="width_medium">
                            <% has_selected = False %>
                            % for option in options:
                                <% 
                                if is_selected(saved_search.alert.expires, option[0], none_value='24h'):
                                    has_selected = True
                                %>
                                <option value="${option[0] | h}"${' selected="selected"' if is_selected(saved_search.alert.expires, option[0], none_value='24h') else ''}>${option[1] | h}</option>
                            % endfor
                            <option value="custom" class="alertExpirationCustomState"${'' if has_selected else 'selected="selected"'}>${_('Custom time')}</option>
                        </select>
                        <div class="indent alertExpirationCustom">
                            <input name="expires_value" type="text" value="${saved_search.time_value(saved_search.alert.expires) or '' | h}"/>
                            <select name="expires_unit"  class="width_short">
                                <% 
                                   options   = [('s', _('second(s)')), ('m', _('minute(s)')), ('h', _('hour(s)')), ('d', _('day(s)'))]
                                   time_unit = saved_search.time_unit(saved_search.alert.expires)
                                   time_unit = 'h' if time_unit == None else time_unit
                                 %>
                                % for option in options:
                                    <option value="${option[0] | h}"${' selected="selected"' if option[0]==time_unit else ''}>${option[1] | h}</option>
                                % endfor
                            </select>
                        </div>
                        <p class="note">
                        	<em>${_('How long <a href="%s" class="spl-icon-external-link-xsm inline-icon" onclick="Splunk.window.openAerts(this.href); return false;">Triggered Alerts</a> keeps a record of each triggered alert.') % make_url(['alerts', app])}</em>
                        </p>
                    </td>
                </tr>
                <tr>
                    <td class="col1"><label for="severity">${_('Severity')}</label></td>
                    <td class="col2">
                        <% severities = ('1', _('Info')), ('2', _('Low')), ('3', _('Medium')), ('4', _('High')), ('5', _('Critical')) %>
                        <select name="alert.severity" class="medium width_short" id="severity">
                            % for option in severities:
                                <option value="${option[0] | h}"${' selected="selected"' if option[0]==saved_search.alert.severity else ''}>${option[1] | h}</option>
                            % endfor
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</div>
<ul class="buttons splClearfix">
    <li class="left">${wizard_cancel_delete(make_url(['alertswizard', app, 'delete']), saved_search.id)}</li>
    <li class="right"><button class="splButton-primary" type="submit" onclick="$(document.forms[0]).trigger('submit');"><span>${_('Next &#187;')}</span></button></li>
    <li class="right"><a href="${make_url(['alertswizard', app, 'step1', 'edit'], _qs=dict(id=saved_search.id)) | h}" class="splButton-secondary"><span>${_('&#171; Back')}</span></a></li>
</ul>
<script type="text/javascript">
    (function(){
        //form behavior
        //condition
        var condition = $("#condition");
        var digestMode = $('#digest_mode');
        var suppressFields = $('#suppressfields');
        var numericCondition = $("table .numericCondition");
        var numericConditionElements = $("select, input", numericCondition);
        var customConditionState = $("table .customCondition");
        var customConditionStateElements = $("input", customConditionState);
        condition.change(function(){
            var selected = condition.find("option:selected");
            if(selected.hasClass("numericConditionState")){
                numericCondition.show();
                numericConditionElements.prop("disabled", false);
                customConditionState.hide();
                customConditionStateElements.prop("disabled", true);
            }else if(selected.hasClass("customConditionState")){
                numericCondition.hide();
                numericConditionElements.prop("disabled", true);
                customConditionState.show();
                customConditionStateElements.prop("disabled", false);
            }else{
                numericCondition.hide();
                numericConditionElements.prop("disabled", true)
                customConditionState.hide();
                customConditionStateElements.prop("disabled", true);
            }
        }).trigger("change");

        digestMode.change(function() {
            var selected = digestMode.find('option:selected').val();
            if (selected == '0') {
                suppressFields.show();
            } else {
                suppressFields.hide();
            }
        }).trigger('change');
        
        //schedule
        var alertPreset = $("#alert_preset");
        var alertCron = $("#alert_cron");
        alertPreset.change(function(){
            if(alertPreset.val()=="cron"){
                alertCron.show();
            }else{
                alertCron.hide();
            }
        }).trigger("change");
        
        //throttling (suppression
        var suppressToggle = $("#suppress_toggle");
        var suppressInputs = $(".suppression div.indent input, .suppression div.indent select");
        suppressToggle.change(function(){
            if(suppressToggle.is(":checked")){
                suppressInputs.prop("disabled", false);
            }else{
                suppressInputs.prop("disabled", true);
            }
        }).trigger("change");
        
        //alert expiration
        var expiration = $("#expiration");
        var alertExpirationCustom = $("table .alertExpirationCustom");
        expiration.change(function(){
            var selected = expiration.find("option:selected");
            if(selected.hasClass("alertExpirationCustomState")){
                alertExpirationCustom.show();
            }else{
                alertExpirationCustom.hide();
            }
        }).trigger("change");
    })()
</script>
