{% load static %}
{% load i18n %}
<head>
    <title>{% trans 'Task log' %}</title>
    <script src="{% static 'js/jquery-3.6.1.min.js' %}"></script>
    <script src="{% static 'js/plugins/xterm/xterm.js' %}"></script>
    <script src="{% static 'js/plugins/xterm/addons/fit/fit.js' %}"></script>
    <link rel="stylesheet" href="{% static 'js/plugins/xterm/xterm.css' %}"/>
    <link rel="shortcut icon" href="{{ INTERFACE.favicon }}" type="image/x-icon">
    <script src="{% url 'javascript-catalog' %}"></script>
    <script src="{% static "js/jumpserver.js" %}?v=10"></script>
    <script>
        (function () {
            var pathname = window.location.pathname || '/'
            var marker = '/core/'
            var idx = pathname.indexOf(marker)
            var prefix = ''
            if (idx > 0) {
                prefix = pathname.slice(0, idx)
            }
            prefix = prefix.replace(/\/+$/, '')
            window.__BASE_PATH__ = prefix
        })()

        function createWsUrl(path) {
            if (/^wss?:\/\//i.test(path)) {
                return path
            }
            const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
            const port = location.port ? ':' + location.port : ''
            return scheme + '://' + location.hostname + port + addBasePath(path)
        }

        function addBasePath(path = '') {
            if (!path || /^https?:\/\//i.test(path)) {
                return path
            }

            const basePath = getBasePath()
            const normalizedPath = path.startsWith('/') ? path : `/${path}`

            if (!basePath) {
                return normalizedPath
            }

            if (
                normalizedPath === basePath ||
                normalizedPath.startsWith(basePath + '/') ||
                normalizedPath.startsWith(basePath + '?') ||
                normalizedPath.startsWith(basePath + '#')
            ) {
                return normalizedPath
            }

            return `${basePath}${normalizedPath}`
        }

        function getBasePath() {
            if (typeof window === 'undefined') {
                return ''
            }
            return window.__BASE_PATH__ || ''
        }
    </script>
    <style>
        body {
            overflow: hidden;
            margin: 0;
        }

        .xterm-rows {
            font-family: "Bitstream Vera Sans Mono", Monaco, "Consolas", Courier, monospace;
            font-size: 13px;
        }

        .container {
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .terminal .xterm-viewport {
            background-color: #1f1b1b;
            overflow: hidden;
        }

        #term {
            flex-grow: 1;
            background-color: black;
            margin: 12px;
            padding: 0 8px;
            border-radius: 4px 0 0 0;
        }

        .info {
            display: flex;
            flex-wrap: wrap;
            padding: 6px 8px 6px 24px;
            margin: 0;
        }

        .task-type {
            font-size: 16px;
            font-weight: 500;
            line-height: 24px;
            text-align: left;
            color: #1F2329;
            padding-bottom: 8px;
        }

        .info .item {
            flex: auto;
            font-size: 14px;
            list-style: none;
        }

        .info .item .label {
            font-weight: 400;
            line-height: 22px;
            font-size: 14px;
            text-align: left;
            color: #646A73;
            padding-bottom: 12px;
        }

        .info .item .value {
            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
            text-align: left;
            color: #1F2329;
        }
    </style>
</head>
<div class="container">
    <div style="position: absolute; top: 10px; right: 12px;">
        <button id="download-log-btn"
                style="background-color: #1ab394; color: white; padding: 5px 10px; border: none; border-radius: 4px; cursor: pointer;">
            {% trans 'Download' %}
        </button>
    </div>
    <div class="header">
        <ul class="info">
            <li class="item">
                <span class="task-type"></span>
            </li>
        </ul>
        <ul class="info">
            <li class="item">
                <span class="label">ID:</span>
                <span class="value task-id"></span>
            </li>
            <li class="item">
                <span class="label">{% trans 'Date start' %}:</span>
                <span class="value date-start"></span>
            </li>
        </ul>
    </div>
    <div id="term">
    </div>
</div>
<script>

    var scheme = document.location.protocol === "https:" ? "wss" : "ws";
    var port = document.location.port ? ":" + document.location.port : "";
    var taskId = "{{ task_id }}";
    var url = "/ws/ops/tasks/log/";
    var wsURL = createWsUrl(url)
    var failOverPort = "{{ ws_port }}";
    var failOverWsURL = scheme + "://" + document.location.hostname + ':' + failOverPort + url;
    var term;
    var ws;
    var vendor = "{{ vendor }}";
    var extraQuery = Object.fromEntries(new URLSearchParams(window.location.search));
    $(document).ready(function () {
        term = new Terminal({
            cursorBlink: false,
            screenKeys: false,
            fontFamily: '"Monaco", "Consolas", "monospace"',
            fontSize: 13,
            lineHeight: 1.2,
            rightClickSelectsWord: true,
            disableStdin: true,
            scrollback: 9999999,
        });
        term.open(document.getElementById('term'));
        window.fit.fit(term);

        ws = new WebSocket(wsURL);
        ws.onmessage = function (e) {
            var data = JSON.parse(e.data);
            var message = data.message;
            if (vendor !== 'jumpserver') {
                message = message.replace(/jumpserver/g, vendor);
            }
            term.write(message);
        };
        ws.onopen = function () {
            var msg = {"task": taskId};
            ws.send(JSON.stringify(msg))
        };
        ws.onerror = function (e) {
            ws = new WebSocket(failOverWsURL);
            ws.onmessage = function (e) {
                var data = JSON.parse(e.data);
                term.write(data.message);
            };
            ws.onerror = function (e) {
                term.write("Connect websocket server error")
            }
        }
        getAutomationExecutionInfo();
    }).on('resize', window, function () {
        window.fit.fit(term);
    });

    function getAutomationExecutionInfo() {
        let url = "{% url 'api-ops:task-executions-detail' pk=task_id %}";

        requestApi({
            url: url,
            method: "GET",
            flash_message: false,
            success(data) {
                const dateStart = data.date_start ? new Date(data.date_start).toLocaleString() : '';
                $('.task-id').html(data.id);
                $('.task-type').html(data.task_name);
                $('.date-start').html(dateStart);
            }
        })
    }

    function downloadLog() {
        term.selectAll()
        let logData = term.getSelection()
        const blob = new Blob([logData], {type: 'text/plain'});
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `log_${taskId}.txt`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }

    document.getElementById('download-log-btn').addEventListener('click', downloadLog);
</script>
