{% 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) {
        data.timestamp = currentDateTimeFormatted();
        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, index) {
        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'];
            document.getElementById('task-alerts-display').appendChild(alert_group);
        }

        var alert = document.getElementById(`${taskId}.${index}`);

        if (!alert) {
            var msg_type = alertData.status.toLowerCase();
            var alert = document.getElementById(`${msg_type}-alert-template`).cloneNode(true).firstElementChild;
            alert.setAttribute('id', `${taskId}.${index}`);
            alert.getElementsByClassName('timestamp')[0].textContent = alertData.timestamp;

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

    function currentDateTimeFormatted() {
        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();
        var hh = String(today.getHours()).padStart(2, '0');
        var minutes = String(today.getMinutes()).padStart(2, '0');
        var secs = String(today.getSeconds()).padStart(2, '0');
        return `${yyyy}/${mm}/${dd} ${hh}:${minutes}:${secs}`
    };

    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);
        }
        getAlertData().forEach(addTaskAlert);
    };
</script>
{% load bootstrap5 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% endblock %}

{% block messages %}
{{ block.super }}
{{ request.user.is_authenticated|json_script:"user_is_authenticated" }}
{% include "task_alerts.html" %}
<script>
    var user_is_authenticated = JSON.parse(document.getElementById('user_is_authenticated').textContent);

    if (user_is_authenticated === true) {
        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;

        getAlertData().forEach(addTaskAlert);
    }
</script>
{% endblock %}
