{% extends 'mainapp/base.html' %}

{% block title %}Статус задачи Lyngsat{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h3 class="mb-0">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-hourglass-split me-2" viewBox="0 0 16 16">
                            <path d="M2.5 15a.5.5 0 1 1 0-1h1v-1a4.5 4.5 0 0 1 2.557-4.06c.29-.139.443-.377.443-.59v-.7c0-.213-.154-.451-.443-.59A4.5 4.5 0 0 1 3.5 3V2h-1a.5.5 0 0 1 0-1h11a.5.5 0 0 1 0 1h-1v1a4.5 4.5 0 0 1-2.557 4.06c-.29.139-.443.377-.443.59v.7c0 .213.154.451.443.59A4.5 4.5 0 0 1 12.5 13v1h1a.5.5 0 0 1 0 1zm2-13v1c0 .537.12 1.045.337 1.5h6.326c.216-.455.337-.963.337-1.5V2zm3 6.35c0 .701-.478 1.236-1.011 1.492A3.5 3.5 0 0 0 4.5 13s.866-1.299 3-1.48zm1 0v3.17c2.134.181 3 1.48 3 1.48a3.5 3.5 0 0 0-1.989-3.158C8.978 9.586 8.5 9.052 8.5 8.351z"/>
                        </svg>
                        Статус задачи заполнения данных Lyngsat
                    </h3>
                </div>
                <div class="card-body">
                    {% if task_id %}
                        <div class="mb-3">
                            <strong>ID задачи:</strong> <code id="task-id">{{ task_id }}</code>
                        </div>

                        <!-- Progress Bar -->
                        <div class="mb-4">
                            <div class="d-flex justify-content-between mb-2">
                                <span id="status-text">Загрузка статуса...</span>
                                <span id="progress-percent">0%</span>
                            </div>
                            <div class="progress" style="height: 25px;">
                                <div id="progress-bar" class="progress-bar progress-bar-striped progress-bar-animated" 
                                     role="progressbar" style="width: 0%;" 
                                     aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                    <span id="progress-text">0%</span>
                                </div>
                            </div>
                        </div>

                        <!-- Task State -->
                        <div id="task-state-container" class="alert alert-info" role="alert">
                            <strong>Состояние:</strong> <span id="task-state">Проверка...</span>
                        </div>

                        <!-- Results Container (hidden by default) -->
                        <div id="results-container" class="d-none">
                            <h5 class="mt-4">Результаты обработки</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="card mb-3">
                                        <div class="card-body">
                                            <h6 class="card-subtitle mb-2 text-muted">Обработано спутников</h6>
                                            <h3 class="card-title" id="result-satellites">-</h3>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card mb-3">
                                        <div class="card-body">
                                            <h6 class="card-subtitle mb-2 text-muted">Обработано источников</h6>
                                            <h3 class="card-title" id="result-sources">-</h3>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card mb-3 border-success">
                                        <div class="card-body">
                                            <h6 class="card-subtitle mb-2 text-success">Создано записей</h6>
                                            <h3 class="card-title text-success" id="result-created">-</h3>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card mb-3 border-info">
                                        <div class="card-body">
                                            <h6 class="card-subtitle mb-2 text-info">Обновлено записей</h6>
                                            <h3 class="card-title text-info" id="result-updated">-</h3>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Errors -->
                            <div id="errors-container" class="d-none">
                                <h6 class="text-danger">Ошибки при обработке:</h6>
                                <div class="alert alert-warning">
                                    <ul id="errors-list" class="mb-0"></ul>
                                </div>
                            </div>
                        </div>

                        <!-- Error Container (hidden by default) -->
                        <div id="error-container" class="alert alert-danger d-none" role="alert">
                            <strong>Ошибка:</strong> <span id="error-text"></span>
                        </div>

                        <!-- Action Buttons -->
                        <div class="d-grid gap-2 d-md-flex justify-content-md-between mt-4">
                            <a href="{% url 'mainapp:fill_lyngsat_data' %}" class="btn btn-secondary">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left me-1" viewBox="0 0 16 16">
                                    <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8"/>
                                </svg>
                                Назад к форме
                            </a>
                            <a href="{% url 'mainapp:actions' %}" class="btn btn-outline-primary" id="actions-btn">
                                Перейти к действиям
                            </a>
                        </div>
                    {% else %}
                        <div class="alert alert-warning" role="alert">
                            ID задачи не указан. Пожалуйста, запустите задачу через форму заполнения данных.
                        </div>
                        <a href="{% url 'mainapp:fill_lyngsat_data' %}" class="btn btn-primary">
                            Перейти к форме
                        </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

{% if task_id %}
<script>
let taskId = '{{ task_id }}';
let pollInterval;
let isCompleted = false;

function updateProgress(data) {
    const statusText = document.getElementById('status-text');
    const progressBar = document.getElementById('progress-bar');
    const progressText = document.getElementById('progress-text');
    const progressPercent = document.getElementById('progress-percent');
    const taskState = document.getElementById('task-state');
    const taskStateContainer = document.getElementById('task-state-container');
    
    // Update state
    taskState.textContent = data.state;
    
    if (data.state === 'PENDING') {
        statusText.textContent = 'Задача в очереди...';
        taskStateContainer.className = 'alert alert-info';
    } else if (data.state === 'PROGRESS') {
        const percent = data.percent || 0;
        statusText.textContent = data.status || 'Обработка...';
        progressBar.style.width = percent + '%';
        progressBar.setAttribute('aria-valuenow', percent);
        progressText.textContent = percent + '%';
        progressPercent.textContent = percent + '%';
        taskStateContainer.className = 'alert alert-info';
    } else if (data.state === 'SUCCESS') {
        statusText.textContent = 'Задача завершена успешно!';
        progressBar.style.width = '100%';
        progressBar.setAttribute('aria-valuenow', 100);
        progressText.textContent = '100%';
        progressPercent.textContent = '100%';
        progressBar.classList.remove('progress-bar-animated');
        progressBar.classList.add('bg-success');
        taskStateContainer.className = 'alert alert-success';
        
        // Show results
        if (data.result) {
            showResults(data.result);
        }
        
        isCompleted = true;
        clearInterval(pollInterval);
    } else if (data.state === 'FAILURE') {
        statusText.textContent = 'Ошибка при выполнении задачи';
        progressBar.classList.remove('progress-bar-animated');
        progressBar.classList.add('bg-danger');
        taskStateContainer.className = 'alert alert-danger';
        
        // Show error
        const errorContainer = document.getElementById('error-container');
        const errorText = document.getElementById('error-text');
        errorText.textContent = data.error || 'Неизвестная ошибка';
        errorContainer.classList.remove('d-none');
        
        isCompleted = true;
        clearInterval(pollInterval);
    }
}

function showResults(result) {
    const resultsContainer = document.getElementById('results-container');
    resultsContainer.classList.remove('d-none');
    
    document.getElementById('result-satellites').textContent = result.total_satellites || 0;
    document.getElementById('result-sources').textContent = result.total_sources || 0;
    document.getElementById('result-created').textContent = result.created || 0;
    document.getElementById('result-updated').textContent = result.updated || 0;
    
    // Show errors if any
    if (result.errors && result.errors.length > 0) {
        const errorsContainer = document.getElementById('errors-container');
        const errorsList = document.getElementById('errors-list');
        errorsContainer.classList.remove('d-none');
        
        errorsList.innerHTML = '';
        result.errors.slice(0, 10).forEach(error => {
            const li = document.createElement('li');
            li.textContent = error;
            errorsList.appendChild(li);
        });
        
        if (result.errors.length > 10) {
            const li = document.createElement('li');
            li.textContent = `И еще ${result.errors.length - 10} ошибок...`;
            li.className = 'text-muted';
            errorsList.appendChild(li);
        }
    }
}

function checkTaskStatus() {
    fetch(`/api/lyngsat-task-status/${taskId}/`)
        .then(response => response.json())
        .then(data => {
            updateProgress(data);
        })
        .catch(error => {
            console.error('Error checking task status:', error);
        });
}

// Start polling
document.addEventListener('DOMContentLoaded', function() {
    checkTaskStatus();
    pollInterval = setInterval(checkTaskStatus, 2000); // Poll every 2 seconds
    
    // Stop polling after 30 minutes
    setTimeout(() => {
        if (!isCompleted) {
            clearInterval(pollInterval);
            document.getElementById('status-text').textContent = 'Превышено время ожидания. Обновите страницу для проверки статуса.';
        }
    }, 30 * 60 * 1000);
});
</script>
{% endif %}
{% endblock %}
