{% extends "pagetemplate.j2.html" %}

{% block title %}Event: {{ name.split("/")[-1] | escape }}{% endblock %}

{% block body %}

<script type="module" src="/static/js/widget.mjs?cache_version=c6d0887e-af6b-11ef-af85-5fc2044b2ae0"></script>
<main>
    <h2>Event {{ name.split("/")[-1]| escape }} of module <a
            href="/modules/module/{{ url(module) }}">{{ module| escape }}</a>
        <span class=error>{{ "(stopped)" if (disabled) else "" }}</span>
    </h2>

    {% if not (module,name) in EventReferences %}
    <span class="danger">Event not active, An error prevented this event from loading.</span>
    {% endif %}

    {% if version == '__draft__' %}
    <p class="warning">This is an unsaved recovered draft version, that could not load because of errors.
        not the actual version that is loaded on the server. Please correct any errors and try saving again,
        or go to the working copy and save that to delete this draft.</p>
    <p class="menubar">
        <a class="button" href="/modules/module/{{ url(module) }}/resource/{{ url(name) }}/__live__">Go to Live
            Version</a>
    </p>
    {% endif %}



    <section class="window" style="min-width: 80%;">

        <small>(Loaded in {{ timetaken}} s)</small>

        <script>
            presubmit = function () {
                document.getElementById('setupbox').value = setupeditor.getValue();
                document.getElementById('actionbox').value = actioneditor.getValue();
            }

            wasChanged = false;

            window.onbeforeunload = function () {
                if (wasChanged) {
                    return "Are you sure you want to exit?";
                }
            }
        </script>
        <form action="/modules/module/{{ url(module) }}/updateresource/{{ url(name) }}" method="POST">
            <h3>Basic</h3>
            <label><input type="checkbox" name="enable" {% if 'enable' in event %} {% if event['enable'] == True %}
                    checked="yes" {% endif %} {% else %} checked="yes" {% endif %}></input>Enable</label>
            <h3 id="setupheading">Setup Code</h3>
            <details class="help">
                <summary><i class="mdi mdi-help-circle-outline"></i></summary>Enter python code. It will execute in the
                event <b>global</b> scope when it loads. If there is any problem,
                the other events will load then this will be retried. This is also how <a
                    href="/docs#dependancies">dependancies</a> are reoslved.
                You will need to use the global keyword in the event action to overwrite a variable defined here.
                {% if not can_edit %}
                <br>
                <span class="warning">You will not be able to save any change made as you are either not logged in or do
                    not have permissions.</span>
                {% endif %}
            </details>

            <textarea data-editor="python" rows=30 class="pythoncode w-full" name="setup" id="setupbox"
                onchange="wasChanged=true" {% if not can_edit %} disabled=1\
                {% endif %}>{{ event.get('setup','pass')| escape }}</textarea>


            <h3>Trigger
                (Currently {{ prevstate| escape }})
            </h3>
            <details class="help">
                <summary><i class="mdi mdi-help-circle-outline"></i></summary>Enter the trigger here. The trigger may
                either be a python expression. Only one copy of each event will poll at a time.
                (by default, event runs when trigger goes from false to true), or a <a href="/docs#trigger">special
                    trigger expression</a>
            </details>


            <input class="pythoncode w-full" id="triggerbox" type="text" name="trigger"
                value="{{ event['trigger']| escape }}" {% if not can_edit %} disabled=1\ {% endif %}
                onchange="wasChanged=true"></input>

            {% if event['trigger'].startswith("!time") %}
            <p style="font-size:90%">Next Run for "{{ event['trigger'][5:]| escape }}":
                {{ formatnextrun() | escape }}</p>
            {% endif %}
            <p style="display:none" id="rrule">Next Run: <span id="rrulespan"></span></p>


            <h3>Additional Trigger Options</h3>
            <div class="max-h-12rem scroll border">
                <input type="checkbox" name="continual" value="false" {% if 'continual' in event %}
                    {% if event['continual'] == True %} checked="yes" {% endif %} {% endif %} {% if not can_edit %}
                    disabled=1\ {% endif %}></input>Do the action repeatedly while the trigger is true<br>
                Do the action at most every:
                <input type="number" name="ratelimit" step=0.01 {% if 'rate_limit' in event %}
                    value="{{ event['rate_limit']| escape }}" {% else %} value="0" {% endif %} {% if not can_edit %}
                    disabled=1\ {% endif %}></input>seconds. Does not affect poll rate(To avoid missing short events).
                <br>

                Polling Priority(to reduce CPU usage, use the lowest possible rate):<select name="priority"
                    {% if not can_edit %} disabled=1\ {% endif %}>
                    <option value="realtime" {{ priority['realtime'] }}>Realtime(as fast as possible)</option>
                    <option value="interactive" {{ priority['interactive'] }}>Interactive(no noticable delay in
                        response)</option>
                    <option value="high" {{ priority["high"] }}>High(response within a second)</option>
                    <option value="medium" {{ priority["medium"] }}>Medium(response within a few seconds)</option>
                    <option value="low" {{ priority["low"] }}>Low(response within a minute)</option>
                    <option value="verylow" {{ priority["verylow"] }}>Very Low(response within a few minutes)</option>
                </select>

            </div>

            <h3>Action</h3>
            <details class="help">
                <summary><i class="mdi mdi-help-circle-outline"></i></summary>
                This code will be executed when the trigger condition is met. Polling will be suspended until the action
                completes.
                <b>NOTE: The Action is scoped like a function body. If you want to assign to variables and have them
                    stay around next time the function runs,
                    you may need to use the global keyword. You may also need to use the global keyword if you get
                    UnboundLocal errors.

                </b>
            </details>

            <textarea data-editor="python" id="actionbox" name="action" rows=50 class="pythoncode w-full"
                onchange="wasChanged=true" {% if not can_edit %} disabled=1\
                {% endif %}>{{ event["action"]| escape }}</textarea>

            {% if (module,name) in EventReferences %}

            <h3>Output</h3>
            {{ EventReferences[module,name].logWindow.render() }}


            <h3>Info</h3>
            <p>
                This event last ran:
                {% if getEventLastRan(module,name) %}
                <b>{{ strftime(getEventLastRan(module,name))| escape }}
                    (about {{ (format_time_interval(time.time()-getEventLastRan(module,name),2)) }} ago)
                </b>



                {% if c %}
                <br>Average Time(Last {{ c }} runs): {{ (format_time_interval(avg_time,2)) }}<br>
                {% endif %}


                {% if EventReferences[module,name].lastcompleted>EventReferences[module,name].lastexecuted %}
                <br>Completed in
                {{ round(EventReferences[module,name].lastcompleted-EventReferences[module,name].lastexecuted,3)| escape }}s
                {% else %}
                <span class="highlight">Still Running</span>
                {% endif %}

                {% else %}
                <b>This event has not ran since it loaded.</b>
                {% endif %}
                <button type="button" onclick="document.getElementById('history').style.display='block'">Show
                    history</button>
                <button type="button" onclick="document.getElementById('history').style.display='none'">Hide
                    history</button>

            <div id="history" style="display:none">
                <table border=1>
                    {% if module,name in EventReferences %}
                    <tr>
                        <th>Started at</th>
                        <th>Completed in</th>
                    </tr>
                    {% for i in EventReferences[module,name].history %}
                    <tr>
                        <td>{{ strftime(i[0]) }}</td>
                        <td>{{ (format_time_interval(i[1]-i[0],2)) }}</td>
                    </tr>
                    {% endfor %}
                    {% endif %}
                </table>
            </div>

            {% if getEventErrors(module,name) %}
            <h3 class="danger">Errors[{{ len(getEventErrors(module,name)) }}]</h3>
            <p class="help">
                This section the most recent errors that ocurred while executing the event or trigger.
            </p>
            <div class="max-h-12rem scroll border">
                {% for i in getEventErrors(module,name) %}
                <h4>{{ i[0]| escape }}</h4>
                <pre>{{ i[1]| escape }}</pre>
                {% endfor %}
            </div>
            {% endif %}

            {% endif %}


            <hr>
            <details class="help">
                <summary><i class="mdi mdi-help-circle-outline"></i></summary>
                Saving this module will case it to completely reload, including its local scope. Other
                resources will not be affected.
            </details>
            {% if can_edit %}
            <input type="submit" value="Save Changes"
                onclick="wasChanged=false; globalThis.kaithemapi.enableWidgetGoneAlert=false">
            {% else %}
            <p>You must have the "system_admin" permission to make changes. Are you logged in?</p>
            {% endif %}
        </form>
        <form method="post" action="/modules/module/{{ url(module) }}/obj/event/{{ url(name) }}"><button>Go to the
                event's namespace(requires edit permission, beware shoulder surfers)</button></form>

    </section>

    <script src="/static/js/thirdparty/src-min-noconflict/ace.js"></script>
    <script src="/static/js/thirdparty/jquery3.js"></script>

    <script>
        // Hook up ACE editor to all textareas with data-editor attribute
        $(function () {
            $('textarea[data-editor]').each(function () {
                var textarea = $(this);
                var mode = textarea.data('editor');
                var editDiv = $('<div>', {
                    position: 'absolute',
                    width: textarea.width(),
                    height: textarea.height(),
                    'class': textarea.attr('class')
                }).insertBefore(textarea);
                textarea.css('display', 'none');
                var editor = ace.edit(editDiv[0]);
                editor.renderer.setShowGutter(false);
                editor.getSession().setValue(textarea.val());
                editor.getSession().setMode("ace/mode/" + mode);
                // editor.setTheme("ace/theme/idle_fingers");
                editor.setOptions({
                    fontFamily: "CodingFont",
                    fontSize: "12pt"
                });
                editor.getSession().on('change', function () {
                    wasChanged = true;
                })
                {% if not can_edit %}
                editor.setReadOnly(true)
                {% endif %}
                // copy back to textarea on form submit...
                textarea.closest('form').submit(function () {
                    textarea.val(editor.getSession().getValue());
                })
            });
        });
    </script>

</main>

<script>
    // Fix going back after a change and seeing old data
    const perfEntries = performance.getEntriesByType('navigation');
    if (perfEntries.length && perfEntries[0].type === 'back_forward') {
        window.location.reload()
    }
</script>

{% endblock %}