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

{% block title %} Tasks {% endblock %}

<!-- Specific Page CSS goes HERE  -->
{% block stylesheets %}
<style>
    #console-container {
        background-color: #1e1e1e; /* Dark background for the main container */
        padding: 15px;
        border-radius: 4px;
        margin-top: 20px;
        overflow-y: auto;
        max-height: 530px;
    }

    #console-container h2 {
        color: #fff; /* White text for the header */
    }

    #sse-data {
        background-color: #1e1e1e; /* Dark background for the main container */
        color: #fff; /* White text */
        font-size: medium;
        font-family: "Courier New";
        white-space: pre-wrap; /* To maintain data formatting */
        padding: 10px; /* Internal spacing */
        border-radius: 4px; /* Rounded borders */
        margin-top: 5px; /* Top margin */
        overflow-y: auto;
    }
.acciones-lineales .dropdown-item {
    display: inline-block;
    margin-right: 10px;
    margin: 0 20px;
}
.acciones-lineales a {
    display: inline-block;
    margin-right: 10px; /* Ajusta el margen según tus necesidades */
}

.linea-divisoria {
    display: inline-block;
    width: 1px; /* Ancho de la línea */
    height: 20px; /* Altura de la línea, ajusta según tus necesidades */
    background-color: #000; /* Color de la línea */
    margin-right: 10px; /* Espacio después de la línea, ajusta según tus necesidades */
    vertical-align: middle; /* Alinea verticalmente con los enlaces */
}
</style>
{% endblock stylesheets %}

{% block content %}
<main class="content">
    {% include 'includes/navigation.html' %}
<div class="beta-version">
    <span class="beta-icon">Console Log -></span>
    <span class="fab fa-docker fa-2x mr-0"></span>
    <p>This is a beta version of the feature. Feedback is welcome!</p>
</div>
    <div class="preloader bg-soft flex-column justify-content-center align-items-center">
        <img class="loader-element animate__animated animate__jackInTheBox" src="/static/assets/img/brand/light.svg" height="90" alt="Volt logo">
    </div>

    <div class="py-4">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb breadcrumb-dark breadcrumb-transparent">
                <li class="breadcrumb-item"><a href="/deploys-list"><span class="fas fa-home"></span></a></li>
                <li class="breadcrumb-item"><a href="/deploys-list">Deploy</a></li>
                <li class="breadcrumb-item"><span class="fas fa-box-open"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.name}}')">{{deploy.name}}</a></li>
                <li class="breadcrumb-item"><span class="fas fa-cloud"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.suqad}}_{{ deploy.environment}}')">{{deploy.squad}}_{{deploy.environment}}</a></li>
                <li class="breadcrumb-item"><span class="fas fa-layer-group"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.stack_name}}')">{{deploy.stack_name}}</a></li>
                <li class="breadcrumb-item"><span class="fa fa-code-branch"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.stack_name}}')">{{deploy.stack_branch}}</a></li>
                <li class="breadcrumb-item"><span class="fas fa-tasks"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.task_id}}')">{{deploy.task_id}}</a></li>
                <li class="breadcrumb-item"><span class="fas fa-sitemap"></span></li>
                <li class="breadcrumb-item">
                <a href="#" onclick="copyToClipboard('{{deploy.action}}')">{{deploy.action}}</a></li>

            </ol>
        </nav>

        <!-- Container to display SSE data in console style -->
        <div id="console-container">
            <h2>Deployment Output:</h2>
            <pre id="sse-data"></pre>
        </div>
    </div>
<div class="acciones-lineales">
    <a href="{{ url_for('.relaunch_console_plan', deploy_id=deploy.id) }}">
       <span class="tag-style-status">PLAN</span>
    </a>
    <span class="linea-divisoria"></span> <!-- Elemento divisor -->
    <a href="{{ url_for('.relaunch_console_deploy', deploy_id=deploy.id) }}">
       <span class="tag-style-apply">APPLY</span>
    </a>
    <span class="linea-divisoria"></span> <!-- Elemento divisor -->
    <a href="#" id="destroyLink">
       <span class="tag-style-failure">DESTROY</span>
    </a>
</div>

<!-- Modal de confirmación -->
<!-- Backdrop for Modal -->
<div id="modalBackdrop" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 2;"></div>

<!-- Confirmation Modal -->
<div id="confirmModal" style="display:none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px; border: 1px solid #ccc; border-radius: 5px; background-color: #f9f9f9; z-index: 3;">
    <p>To confirm, enter the name of the deploy:</p>
    <input type="text" id="deploymentNameInput" placeholder="Deploy Name" style="padding: 5px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 3px; width: 100%;">
    <p id="errorMessage" style="color: red; display: none;">Name does not match.</p>
    <button id="confirmDestroy" style="background-color: var(--bs-reddit); color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer;">Confirm Destruction</button>
    <button id="cancelDestroy" style="background-color: var(--bs-soft-green); color: white; padding: 10px 15px; margin-left: 10px; border: none; border-radius: 5px; cursor: pointer;">Cancel</button>
</div>
    {% include 'includes/footer.html' %}
    
</main>
{% endblock content %}

<!-- Specific Page JS goes HERE  -->
{% block javascripts %}
<script>
    const taskId = "{{ deploy.task_id }}";

    // Establishes the SSE connection with the correct endpoint
    const eventSource = new EventSource(`/stream/${taskId}`);
    eventSource.onmessage = function(e) {
        const sseDataElement = document.getElementById('sse-data');

        if (e.data !== '1' && e.data !== 'null') {
            // Handle normal data, excluding 'null'
            sseDataElement.textContent += e.data + '\n';
            setTimeout(() => {
                const lastLine = document.createElement("div");
                sseDataElement.appendChild(lastLine);
                lastLine.scrollIntoView({ behavior: "smooth", block: "end" });
            }, 30); 
        } else if (typeof e.data === 'string') {
            // Handle the case where '1' is received - fetch additional data
            fetch('/output/' + taskId)
                .then(response => response.json()) // Parse the JSON response
                .then(dataArray => {
                    if (dataArray && dataArray.length > 0) {
                        // Iterate over each string in the array and append it, excluding 'null'
                        dataArray.forEach(item => {
                            if (item && item !== 'null') {
                                sseDataElement.textContent += item + '\n';
                            }
                        });
                    } else {
                        sseDataElement.textContent = 'No additional task data available.';
                    }
                })
                .catch(error => {
                    console.error('Error fetching additional task data:', error);
                    sseDataElement.textContent = 'No fetching data.';
                });
        }
    };
</script>
<script src="/static/assets/js/copy_clipboard.js"></script>

<script>
    document.getElementById('destroyLink').addEventListener('click', function(event) {
        event.preventDefault();
        document.getElementById('modalBackdrop').style.display = 'block';
        document.getElementById('confirmModal').style.display = 'block';
    });

    document.getElementById('confirmDestroy').addEventListener('click', function() {
        var enteredName = document.getElementById('deploymentNameInput').value;
        if (enteredName === '{{ deploy.name }}') {
            window.location.href = '{{ url_for('.destroy_deploy_console', deploy_id=deploy.id) }}';
        } else {
            document.getElementById('errorMessage').style.display = 'block';
        }
    });

    document.getElementById('cancelDestroy').addEventListener('click', function() {
        document.getElementById('modalBackdrop').style.display = 'none';
        document.getElementById('confirmModal').style.display = 'none';
        document.getElementById('errorMessage').style.display = 'none';
    });
</script>
{% endblock javascripts %}
