<%namespace file="../lib.html" import="fillform"/>
<%namespace file="../lib.html" import="script_tags"/>
<%namespace file="../lib.html" import="stylesheet_tags"/>
<%namespace file="../lib.html" import="csrf_hidden_input"/>
<%namespace file="_helpers.html" import="generateFormRow"/>
<%namespace name="helpers" file="_helpers.html"/>

<%
sessionId = cherrypy.session.id

import splunk.auth
import splunk.entity as en
from splunk.appserver.mrsparkle.lib.msg_pool import MsgPoolMgr, UI_MSG_POOL

jmFormActionsStyle = ''
isEmbedded = splunk.util.normalizeBoolean(cherrypy.request.params.get('embedded'))
if isEmbedded:
    jmFormActionsStyle = 'display:none;'
%>
<%call expr="stylesheet_tags(cssFiles)"></%call>

% if uiHelper:
    <script type="text/javascript">
    function handleEditFormSubmit(ev) {
        
        var frm = $('#eaiform');
        var eai = Splunk.EAI.getInstance();
        if (!eai)
            return false; // page not yet loaded?
            // eai.confirmSubmission = true;
            // eai.confirmQuestion = _("Submitting this form will switch you to LDAP configuration, make sure you write down your failsafe login information or you won't be able to login.");
        eai.saveForm(frm);
        return false;    
    }

    function handleCancelButtonClick() {
        % if kwargs.get('redirect_override_cancel'):
            window.location = ${ jsonify(make_url(kwargs['redirect_override_cancel'])) };
        % else:
            var IEregex = /(?=.*msie ([\d.]+))|(?=.*trident)(?=.*rv\:([\d.]+))/i;
            var isIE = IEregex.test(window.navigator.userAgent);

            if (((isIE && history.length > 0) || (!isIE && history.length > 1)) 
                && document.referrer.indexOf('/account/login?') === -1) {
                // you have history and you are not visiting from login page 
                history.go(-1);
            }else{
                // you do not have history or you might be visiting from login page
                // redirect to manager page
                window.location = Splunk.util.make_url('manager', '${namespace|h}', '${endpoint_base|h}');
            }
        % endif
        return false;
    }

    </script>
% endif

    <%
    msg_obj = MsgPoolMgr.get_poolmgr_instance()[UI_MSG_POOL].pop(msgid)
    %>
    % if msg_obj:
        <%helpers:message content="${msg_obj.text}" level="${msg_obj.severity}"/>
    % endif
<div class="editFormWrapper">
<div class="splOverlay-white"></div>
<div id="loadingmessage">${_('Loading...')}</div>

% if form_defaults:
        <%
        if isCloneAction:
            save_to = "_new"
        else:
            save_to = entity_name
        %>    
        <%
        actionPath = make_url(["manager", namespace, endpoint_base, en.quoteEntity(save_to)])
        eaiAttributes = form_defaults['eai:attributes']
        edit_links = filter((lambda x: x[0] == 'edit'), entity.links)
        entity['__ns'] = entity.namespace
        if isCloneAction:
            isEditable = entity.isClonable
        else:
            isEditable = not (entity.name != '_new' and not edit_links)
        %>

        % if not isEditable:
        <div class="error">
          ${_("You do not have permissions to edit this configuration.")}
        </div>
        % endif

        ## Used to display errors inside a popup window instead of using the messenger

        <div class="EAIError error"></div>
        <form \
            id="eaiform" \
            name="${endpoint_base|h}" \
            class="entityEditForm" \
            method="post" \
            action="${actionPath}" \
            enctype="multipart/form-data" \
            autocomplete="off"
            >
        <!--h2>${breadcrumbs[len(breadcrumbs) - 1][0]|h}</h2--> 
        % if not '__ns' in uiHelper_elements:
          <input type="hidden" name="__ns" value="${entity.namespace | h}">
        % endif

        % if isCloneAction:
          <input type="hidden" name="__action" value="clone">
          % if '__clonesource' in kwargs:
            <input type="hidden" name="__clonesource" value="${kwargs['__clonesource'] | h}">
          % endif
        % elif entity.name == '_new':
          <input type="hidden" name="__action" value="new">
        % else:
          <input type="hidden" name="__action" value="edit">
        % endif

        ## pass through index page filter settings 
        % for key in kwargs.keys():
            % if key.startswith('f_'):
              <input type="hidden" name="__${key}" value="${kwargs[key] | h}">
            % endif
        % endfor

        <input type="hidden" name="__redirect" value="">
        % if isCloneAction and 'eai:type' in form_defaults and form_defaults['eai:type'] == 'html':
            <input type="hidden" name="eai:type" value="${form_defaults['eai:type'] | h}">
        % endif
        % if uiHelper:
            <%call expr="fillform(form_defaults, form_errors)"> <!-- fillform will fill out default values and error messages for us -->
            <div class="formWrapper">
                % if "elements" in uiHelper:
                    % for element in uiHelper["elements"]:
                        <% if not isEditable: element['disabled'] = '1' %>
                        <%call expr="generateFormRow(element, eaiAttributes, form_defaults)"></%call>
                    % endfor
                % endif
            </div>
            </%call>
            ${csrf_hidden_input()}
            % if not eleOnly:
                <div class="jmFormActions" style="${jmFormActionsStyle}">
                    <button class="splButton-secondary" type="button" accesskey="c"><span><%doc>TRANS: Cancel editing the item</%doc>${_('Cancel')}</span></button>
                    % if edit_links and entity.name != "_new" and not isCloneAction:
                        <input type="hidden" name="__uri" value="${edit_links[0][1] | h}">
                    % endif
                    % if isEditable:
                       <button type="submit" class="splButton-primary" accesskey="s"><span><%doc>TRANS: Save the item</%doc>${_('Save')}</span></button>
                    % endif
                </div>
            % endif
            % if kwargs.get('redirect_override') :
                <input type="hidden" name="spl-ctrl_redirect_override" value="${kwargs.get('redirect_override') | h}" />
            % endif
        % endif
        </form>
% endif

</div>

<script type="text/javascript">
function initEAIForm() {
    var eai = Splunk.EAI.getInstance(
        ${jsonify(uiHelper_elements)}, // eaicfg
        ${endpoint_base|jsonify}, // endpoint_base
        ${jsonify(form_defaults['eai:attributes'])} // eai_attributes
    );
    // bind the submit handler
    var frm = $('#eaiform');
    frm.submit(handleEditFormSubmit);
    $('.splButton-secondary').click(handleCancelButtonClick);

    // final setup
    eai.handleAdminReady(${namespace|jsonify}, ${entity.name|jsonify});
}
function doElementOnChange(el, elname) {
    Splunk.EAI.getInstance().doElementOnChange(el, elname);
}

// Make sure the form is initialized at page load for /manager
// initEAIForm() is called explicitly if loaded as a popup
$(initEAIForm);
</script>
