<%!
from splunk.appserver.mrsparkle.lib import util
from splunk.appserver.mrsparkle.lib.eai import cpQuoteEntity
%>\
<%page expression_filter="h"/>\
<%namespace name="lib" file="/lib.html" import="get_application_css" />\
<!doctype html>
<head>
    <meta charset="utf-8" />
    <title>${_('search editor')}</title>
    <meta name="description" content="${_('panel search editor')}" />
    <link rel="stylesheet" href="${make_url('/static/css/view.css')}" />
    <link rel="stylesheet" href="${make_url('/static/css/skins/default/default.css')}" />
    ${lib.get_application_css(app)}
    <style>
        input, textarea, select {
            margin: 0px;
            padding: 4px 5px;
        }
        textarea {
            width: 308px;
            height: 100px;
            display: block;
            resize: none;
        }
        input[type="text"] {
            width: 130px;
            text-align: right;
        }
        input[disabled], textarea[disabled] {
            background-color: #f4f4f1;
            border: none;
            padding: 5px;
        }
        label {
            line-height: 23px;
        }
        a {
            font-size: 12px;
            margin-right: 10px;
        }
        .saved-search-container ul,
        .inline-search-string ul {
            list-style: none;
            margin-left: 0px;
            padding: 10px 10px 0px;
        }
        .saved-search-container ul li,
        .inline-search-string ul li {
            margin-bottom: 15px;
        }
        .readonlyform,
        input[type="text"].readonlyform {
            border: 1px solid #CCC;
            background: #f4f4f1;
            box-shadow: none;
        }
        input[type="text"].readonlyform {
            width: 130px;
        }
        .search-type {
            padding: 5px 10px;
            background: #ededed url(/static/img/skins/default/overlay_bottomgradient_soft.png) repeat-x bottom;
            border-bottom: 1px solid #ccc;
        }
        .search-type label {
            margin-right: 10px;
            text-shadow: 0px 1px 0px white;
        }
        .saved-search-list, .inline-search-header {
            padding: 7px 11px;
            border-bottom: 1px solid #ccc;
            position: relative;
        }
        .saved-search-list:after, .inline-search-header:after {
            content: '';
            border-bottom: 1px solid #f5f5f5;
            display: block;
            position: absolute;
            left: 0;
            right: 0;
            bottom: -2px;
        }

        
        .saved-search-list select {
            width: 100%;
        }
        .saved-search-container,
        .inline-search-string {
            padding: 0px;
        }
        a.edit {
            background: transparent url(/static/img/skins/default/paneleditor/sprite-colorrange.png) no-repeat 0px -64px;
            padding-left: 14px;
        }
        .search-links,
        .search-schedule {
            clear: both;
        }
        .search-time-range label, .search-time-range input {
            float: left;
        }
        .search-time-range-desc {
            text-align: center;
        }
        .help-text {
            clear:both;
            color:#666;
        }
        .help-text em {
            font-style: italic;
        }
        .help-text .spl-external-link {
            font-size: 11px;
        }
        .actions {
            padding-top: 10px;
        }
    </style>
</head>
<body style="padding:0px; margin:0px;">
    <form method="post" action="${make_url(['paneleditor', app, 'searchupdate', dashboard_panel.id[1][0], dashboard_panel.id[1][1]], _qs=dict(id=dashboard_panel.id[0]))}">
        <input type="hidden" name="splunk_session_id" value="${cherrypy.session.id}"/>
        <div class="saved-search">
            <div class="saved-search-list">
                <label for="search-saved">${_('Saved search')}</label>
                <select name="panel_model.searchCommand">
                    % for saved_searches_item in saved_searches:
                        <option value="${saved_searches_item.id}" ${'selected="selected"' if saved_searches_item.id==saved_search.id else '' | n}>${saved_searches_item.name}</option>
                    % endfor
                </select>


                <div class="actions">
                    % if saved_search.id:
                        <%
                        saved_search_manager_url = make_url(
                            ['manager', app, 'saved/searches', cpQuoteEntity(saved_search.name, urlquote=False)],
                            _qs=dict(
                                app=app,
                                owner=saved_search.owner,
                                search='"' + cpQuoteEntity(saved_search['name'], urlquote=False) + '"',
                                uri=saved_search.id,
                                redirect_override="/app/%s/%s" % (app, dashboard.name),
                                action='edit'
                            )
                        )
                        %>
                        <a href="${saved_search_manager_url}" class="edit" onclick="parent.location.href=this.href;">${_('Edit in manager')}</a>
                    % endif
                    <a href="#" class="edit inlineEdit">${_('Edit as an inline search')}</a>
                </div>
            </div>

            <div class="saved-search-container">
                <ul>
                    <li class="search-string">
                        <label for="panel_model.searchCommand">${_('Search string')}</label>
                        <a href="${make_url(['app', app, 'flashtimeline'], _qs=dict(s=saved_search.name))}" class="spl-icon-external-link-xsm" target="_blank">${_('Run search')}</a>
                        <textarea name="panel_model.searchCommand" readonly="readonly" class="readonlyform">${saved_search.search}</textarea>
                    </li>

                    <li class="search-time">
                        <label for="search_earliest_time">${_('Time range')}</label>

                        <div class="search-time-range">
                            <input type="text" name="panel_model.searchEarliestTime" id="search_earliest_time" value="${saved_search.dispatch.earliest_time or ''}" readonly="readonly" class="readonlyform"/>
                            <label class="search-time-range-desc" for="search_latest_time">${_('to')}</label>
                            <input type="text" name="panel_model.searchLatestTime" id="search_latest_time" value="${saved_search.dispatch.latest_time or ''}" readonly="readonly" class="readonlyform"/>
                            <div class="note help-text">
                                <em>
                                    ${_("""Time specifiers: y, mon, d, h, m, s""")}
                                    <a href="${generateSelfHelpLink('learnmore.alert.relativetime')}" target="_blank" title="${_('Splunk help')}" class="spl-external-link spl-icon-external-link-xsm">${_('Learn more')}</a>
                                </em>
                            </div>
                        </div>
                    </li>
                    % if saved_search.schedule.is_scheduled:
                        <li class="search-schedule">
                            <label for="search-schedule">${_('Search schedule')}</label>
                            <div>
                                <input type="text" name="search-schedule" id="search-schedule" class="readonlyform" readonly="readonly" value="${saved_search.schedule.cron_schedule}" readonly="readonly" class="readonlyform"/>
                            </div>
                        </li>
                    % endif
                </ul>
            </div>
        </div>

        <div class="inline-search-string">
            <div class="inline-search-header">
                <label>${_('Inline search')}</label>
                <div class="">
                    <a href="#" class="edit">${_('Select a saved search')}</a>
                </div>
            </div>

            <ul>
                <li class="search-string">
                    <label for="panel_model.searchCommand">${_('Search string')}</label>
                    <a href="${make_url(['app', app, 'flashtimeline'], _qs=dict(s=inline_search.name))}" class="spl-icon-external-link-xsm" target="_blank">${_('Run search')}</a>
                    <textarea name="panel_model.searchCommand">${inline_search.search or ''}</textarea>
                </li>

                <li class="search-time">
                    <label for="search_earliest_time_inline">${_('Time range')}</label>

                    <div class="search-time-range">
                        <input type="text" name="panel_model.searchEarliestTime" id="search_earliest_time_inline" value="${inline_search.dispatch.earliest_time or ''}"/>
                        <label class="search-time-range-desc" for="search_latest_time">${_('to')}</label>
                        <input type="text" name="panel_model.searchLatestTime" id="search_latest_time_inline" value="${inline_search.dispatch.latest_time or ''}"/>
                    </div>

                    <div class="note help-text">
                        <em>
                            ${_("""Time specifiers: y, mon, d, h, m, s""")}
                            <a href="${generateSelfHelpLink('learnmore.alert.relativetime')}" target="_blank" title="${_('Splunk help')}" class="spl-external-link spl-icon-external-link-xsm">${_('Learn more')}</a>
                        </em>
                    </div>
                </li>
            </ul>
        </div>

        <ul class="splClearfix buttons" style="margin:0px; margin-top:10px; background: #fff; border-top: 1px solid #ccc;padding:10px; list-style:none;">
            <li style="float:left;"><a href="${make_url(['paneleditor', app, 'searchedit', dashboard_panel.id[1][0], dashboard_panel.id[1][1]], _qs=dict(id=dashboard_panel.id[0]))}" class="splButton-secondary cancel" tabindex="3">${_("Cancel")}</a></li>
            <li style="float:right;"><button class="splButton-primary" type="button"><span>${_('Save')}</span></button></li>
        </ul>
    </form>
    <script src="${make_url('/static/js/contrib/deprecated/jquery-1.8.3.js')}"></script>
    <script>
        (function(){
            var uiSearchMode = ${json_decode(ui_search_mode)|n};
            function selectSaved(val){
                window.location.href = ${json_decode(make_url(['paneleditor', app, 'searchedit', dashboard_panel.id[1][0], dashboard_panel.id[1][1]], _qs=dict(id=dashboard_panel.id[0])))|n} + '&saved_search_id=' + encodeURIComponent(val);
            }
            function showSaved(){
                $('.inline-search-string').hide();
                $('.saved-search').show();
            }
            function showInline(){
                $('.inline-search-string').show();
                $('.saved-search').hide();
            }
            //constructor
            if(uiSearchMode=='saved'){
                showSaved();
            }else{
                showInline();
            }
            //DOM event listeners
            $("select").bind('change', function(){
                selectSaved($(this).val());
            });
            $(".search-string a").bind('click', function(){
                var href;
                var base = ${json_decode(make_url(['app', app, 'flashtimeline']))|n};
                if(uiSearchMode=='saved'){
                    href = base + "?s=" + encodeURIComponent($("select option:selected").html());
                }else{
                    href = base + "?q=" + encodeURIComponent($('.inline-search-string textarea').val());
                }
                this.href = href;
            });
            $(".inline-search-string a.edit").bind('click', function() {
                uiSearchMode = 'saved';
                showSaved();
                return false;
            });
            $('.saved-search .inlineEdit').bind('click', function(){
                uiSearchMode = 'string';
                showInline();
                $('.inline-search-string textarea[name="panel_model.searchCommand"]').attr('value', $('.saved-search textarea[name="panel_model.searchCommand"]').attr('value'));
                $('.inline-search-string input[name="panel_model.searchEarliestTime"]').attr('value', $('.saved-search input[name="panel_model.searchEarliestTime"]').attr('value'));
                $('.inline-search-string input[name="panel_model.searchLatestTime"]').attr('value', $('.saved-search input[name="panel_model.searchLatestTime"]').attr('value'));
                return false;
            });

            //save to backend
            $('.splButton-primary').bind('click', function(){
                var searchCommand, searchEarliestTime, searchLatestTime;
                if(uiSearchMode=='saved'){
                    searchCommand = $('.saved-search select[name="panel_model.searchCommand"] option:selected').html();
                    searchEarliestTime = '';
                    searchLatestTime = '';
                }else{
                    searchCommand =  $('.inline-search-string textarea[name="panel_model.searchCommand"]').attr('value');
                    searchEarliestTime = $('.inline-search-string input[name="panel_model.searchEarliestTime"]').attr('value');
                    searchLatestTime = $('.inline-search-string input[name="panel_model.searchLatestTime"]').attr('value');
                }
                var params = {
                    url: $('form').attr('action'),
                    type: 'POST',
                    timeout: 50000,
                    headers: {
                        'X-Splunk-Form-Key': ${json_decode(util.getFormKey())|n}
                    },
                    data: {
                        'panel_model.searchMode' : uiSearchMode,
                        'panel_model.searchCommand':  searchCommand,
                        'panel_model.searchEarliestTime' : searchEarliestTime,
                        'panel_model.searchLatestTime' : searchLatestTime
                    },
                    complete: function(response) {
                        if (response.status==200) {
                            //iframe friendly custom events
                            if (window.top===window.self) {
                                alert('${_('Your panel changes have been saved.')}');
                            }
                            parent.$(parent.document).trigger('panelsave');
                        } else {
                            //iframe friendly custom events
                            parent.$(parent.document).trigger('panelerror');
                            var data, invalidEarliestTime, invalidLatestTime;
                            try {
                                data = JSON.parse(response.responseText);
                            } catch(e) {}
                            if (data && data.error && $.inArray('Invalid earliest time', data.error) > -1) {
                                alert('${_('Error:\\nInvalid earliest time.')}');
                            } else if (data && data.error && $.inArray('Invalid latest time', data.error) > -1) {
                                alert('${_('Error:\\nInvalid latest time.')}');
                            } else {
                                if(data.error[0]) {
                                    alert(data.error[0])
                                } else {
                                    alert('${_('Error:\\nYour panel changes could not be saved.')}');
                                }
                            }
                        }
                    }
                };
                $.ajax(params);
            });
       })();
    </script>
</body>
</html>
