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

{% block extrahead %}
{{ block.super }}
<script>
    function getAlertData() {
        sessionStorage.getItem('alerts') || sessionStorage.setItem('alerts', JSON.stringify([]));
        return JSON.parse(sessionStorage.getItem('alerts'))
    }

    function pushAlert(data) {
        const alerts = getAlertData();
        alerts.push(data);
        sessionStorage.setItem('alerts', JSON.stringify(alerts));
    }

    function dismissAlerts(memoryID) {
        const alerts = getAlertData().filter((it) => it['memory-id'] != memoryID);
        sessionStorage.setItem('alerts', JSON.stringify(alerts));
    }

    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.addEventListener('closed.bs.alert', () => dismissAlerts(taskId));
        }

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

        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['exception-repr'];
        }
        if (msg_type == 'badrequest') {
           alert.getElementsByTagName('pre')[0].innerHTML = JSON.stringify(alertData.details);
        }

        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()}`
    };

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

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

    function wsOnError(event) {
        console.error('WebSocket error:', event);
    };

    function wsOnMessage(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') {
            pushAlert(msg.content);
        }
    };

    var admin_ws = admin_ws || new WebSocket(
        `${(location.protocol === 'https:') ? 'wss' : 'ws'}://${window.location.host}{{ websocket_uri }}`
    );
    admin_ws.onopen = wsOnOpen;
    admin_ws.onclose = wsOnClose;
    admin_ws.onerror = wsOnError;
    admin_ws.onmessage = wsOnMessage;
</script>
{% load bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% endblock %}

{% block messages %}
{{ block.super }}
{% include "task_alerts.html" %}
<script>
    getAlertData().forEach(addTaskAlert);
</script>
{% endblock %}
