{% extends "admin/change_list.html" %}

{% block extrahead %}
{{ block.super }}
<script>
    var admin_ws = admin_ws || new WebSocket('ws://' + window.location.host + '{{ websocket_uri }}');

    admin_ws.onopen = function (event) {
        console.log('WebSocket connection opened:', event);
    };

    admin_ws.onclose = function (event) {
        console.log('WebSocket connection closed:', event);
    };

    admin_ws.onerror = function (event) {
        console.error('WebSocket error:', event);
    };

    admin_ws.onmessage = function (msg_event) {
        console.log('WebSocket message received:', msg_event.data);
        const msg = JSON.parse(msg_event.data);
        const group = msg.type.split('.')[0];
        if (group == 'task') { addTaskAlert(msg.content); };
    };

    function addTaskAlert(alertData) {
        const taskId = alertData['memory-id'];
        delete alertData['memory-id'];
        var alert_group = document.getElementById(taskId);

        if (!alert_group) {
            var alert_group = document.getElementById('alert-group-template').cloneNode(true).firstElementChild;
            alert_group.setAttribute('id', taskId);
        }

        alert_group.getElementsByClassName('task-name')[0].innerHTML = `${alertData.name}_${taskId}`;
        delete alertData['name'];

        var msg_type = alertData.status.toLowerCase();
        var alert = document.getElementById(`${msg_type}-alert-template`).cloneNode(true).firstElementChild;
        if (msg_type == 'success') {
            alert.getElementsByTagName('code')[0].innerHTML = alertData.output;
        }
        if (msg_type == 'error') {
            alert.getElementsByTagName('pre')[0].innerHTML = alertData.traceback.join('');
        }

        alert_group.getElementsByClassName('task-alerts')[0].appendChild(alert);
        alert_group.getElementsByClassName('last-updated')[0].textContent = currentDateFormatted();
        document.getElementById('task-alerts-display').appendChild(alert_group);
    };

    function currentDateFormatted() {
        var today = new Date();
        var dd = String(today.getDate()).padStart(2, '0');
        var mm = String(today.getMonth() + 1).padStart(2, '0');
        var yyyy = today.getFullYear();
        return `${yyyy}/${mm}/${dd} at ${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`
    };
</script>
{% load bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% endblock %}

{% block messages %}
{{ block.super }}
{% include "task_alerts.html" %}
{% endblock %}
