{% extends "mainapp/base.html" %}
{% load static %}

{% block title %}Ввод данных{% endblock %}

{% block extra_css %}
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
<style>
    .data-entry-container {
        padding: 20px;
    }
    .form-section {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }
    .table-section {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    #data-table {
        margin-top: 20px;
        font-size: 12px;
    }
    #data-table .tabulator-header {
        font-size: 12px;
        white-space: normal;
        word-wrap: break-word;
    }
    #data-table .tabulator-header .tabulator-col {
        white-space: normal;
        word-wrap: break-word;
        height: auto;
        min-height: 40px;
    }
    #data-table .tabulator-header .tabulator-col-content {
        white-space: normal;
        word-wrap: break-word;
        padding: 6px 4px;
    }
    #data-table .tabulator-cell {
        font-size: 12px;
        padding: 6px 4px;
    }
    .btn-group-custom {
        margin-top: 15px;
    }
    .input-field {
        font-family: monospace;
    }
</style>
{% endblock %}

{% block content %}
<div class="data-entry-container">
    <h2>Ввод данных точек спутников</h2>
    
    <div class="form-section">
        <div class="row">
            <div class="col-md-4 mb-3">
                <label for="satellite-select" class="form-label">Спутник</label>
                <select id="satellite-select" class="form-select">
                    <option value="">Выберите спутник</option>
                    {% for satellite in satellites %}
                    <option value="{{ satellite.id }}">{{ satellite.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-8 mb-3">
                <label for="data-input" class="form-label">Данные</label>
                <input type="text" id="data-input" class="form-control input-field" 
                       placeholder="Вставьте строку данных и нажмите Enter">
            </div>
        </div>
    </div>
    
    <div class="table-section">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h5>Таблица данных <span id="row-count" class="badge bg-primary">0</span></h5>
            </div>
            <div class="btn-group-custom">
                <button id="export-xlsx" class="btn btn-success">
                    <i class="bi bi-file-earmark-excel"></i> Сохранить в Excel
                </button>
                <button id="clear-table" class="btn btn-danger ms-2">
                    <i class="bi bi-trash"></i> Очистить таблицу
                </button>
            </div>
        </div>
        
        <div id="data-table"></div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
<script src="{% static 'sheetjs/xlsx.full.min.js' %}"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Tabulator
    const table = new Tabulator("#data-table", {
        layout: "fitDataStretch",
        height: "500px",
        placeholder: "Нет данных. Введите данные в поле выше и нажмите Enter.",
        headerWordWrap: true,
        columns: [
            {title: "Объект наблюдения", field: "object_name", minWidth: 180, widthGrow: 2, editor: "input"},
            {title: "Частота, МГц", field: "frequency", minWidth: 100, widthGrow: 1, editor: "input"},
            {title: "Полоса, МГц", field: "freq_range", minWidth: 100, widthGrow: 1, editor: "input"},
            {title: "Символьная скорость, БОД", field: "bod_velocity", minWidth: 120, widthGrow: 1.5, editor: "input"},
            {title: "Модуляция", field: "modulation", minWidth: 100, widthGrow: 1, editor: "input"},
            {title: "ОСШ", field: "snr", minWidth: 70, widthGrow: 0.8, editor: "input"},
            {title: "Дата", field: "date", minWidth: 100, widthGrow: 1, editor: "input"},
            {title: "Время", field: "time", minWidth: 90, widthGrow: 1, editor: "input"},
            {title: "Зеркала", field: "mirrors", minWidth: 130, widthGrow: 1.5, editor: "input"},
            {title: "Местоопределение", field: "location", minWidth: 130, widthGrow: 1.5, editor: "input"},
            {title: "Координаты", field: "coordinates", minWidth: 150, widthGrow: 2, editor: "input"},
        ],
        data: [],
    });
    
    // Update row count
    function updateRowCount() {
        const count = table.getDataCount();
        document.getElementById('row-count').textContent = count;
    }
    
    // Listen to table events
    table.on("rowAdded", updateRowCount);
    table.on("dataChanged", updateRowCount);
    
    // Parse input string
    function parseInputString(inputStr) {
        const parts = inputStr.split(';');
        
        if (parts.length < 5) {
            return null;
        }
        
        // Parse date and time (first part)
        const dateTimePart = parts[0].trim();
        const dateTimeMatch = dateTimePart.match(/(\d{2}\.\d{2}\.\d{4})\s+(\d{2}:\d{2}:\d{2})/);
        
        if (!dateTimeMatch) {
            return null;
        }
        
        const date = dateTimeMatch[1];
        const time = dateTimeMatch[2];
        
        // Parse object name (second part)
        const objectName = parts[1].trim();
        
        // Parse location (fourth part - "Позиция")
        // const location = parts[3].trim() || '-';
        const location = '-';
        
        // Parse coordinates (fifth part)
        const coordsPart = parts[4].trim();
        const coordsMatch = coordsPart.match(/([-\d,]+)\s+([-\d,]+)/);
        
        let coordinates = '-';
        if (coordsMatch) {
            const lat = coordsMatch[1].replace(',', '.');
            const lon = coordsMatch[2].replace(',', '.');
            coordinates = `${lat}, ${lon}`;
        }
        
        return {
            date: date,
            time: time,
            object_name: objectName,
            location: location,
            coordinates: coordinates,
        };
    }
    
    // Search for ObjItem data
    async function searchObjItemData(objectName, satelliteId, latitude, longitude) {
        try {
            const params = new URLSearchParams({
                name: objectName,
            });
            
            if (satelliteId) {
                params.append('satellite_id', satelliteId);
            }
            
            if (latitude && longitude) {
                params.append('latitude', latitude);
                params.append('longitude', longitude);
            }
            
            const response = await fetch(`/api/search-objitem/?${params.toString()}`);
            const data = await response.json();
            
            return data;
        } catch (error) {
            console.error('Error searching ObjItem:', error);
            return { found: false };
        }
    }
    
    // Handle input
    const dataInput = document.getElementById('data-input');
    const satelliteSelect = document.getElementById('satellite-select');
    
    dataInput.addEventListener('keypress', async function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            
            const inputValue = this.value.trim();
            
            if (!inputValue) {
                alert('Введите данные');
                return;
            }
            
            // Disable input while processing
            this.disabled = true;
            
            try {
                // Parse input
                const parsedData = parseInputString(inputValue);
                
                if (!parsedData) {
                    alert('Неверный формат данных. Проверьте формат строки.');
                    return;
                }
                
                // Search for ObjItem data
                const satelliteId = satelliteSelect.value;
                
                // Extract latitude and longitude from coordinates
                let latitude = null;
                let longitude = null;
                if (parsedData.coordinates && parsedData.coordinates !== '-') {
                    const coordParts = parsedData.coordinates.split(',').map(c => c.trim());
                    if (coordParts.length === 2) {
                        latitude = coordParts[0];
                        longitude = coordParts[1];
                    }
                }
                
                const objItemData = await searchObjItemData(
                    parsedData.object_name, 
                    satelliteId, 
                    latitude, 
                    longitude
                );
                
                // Show warning if object not found
                if (!objItemData.found) {
                    console.warn('Объект не найден в базе данных:', parsedData.object_name);
                }
                
                // Prepare row data
                const rowData = {
                    object_name: parsedData.object_name || '-',
                    date: parsedData.date || '-',
                    time: parsedData.time || '-',
                    location: parsedData.location || '-',
                    coordinates: parsedData.coordinates || '-',
                    frequency: objItemData.found && objItemData.frequency !== null ? objItemData.frequency : '-',
                    freq_range: objItemData.found && objItemData.freq_range !== null ? objItemData.freq_range : '-',
                    bod_velocity: objItemData.found && objItemData.bod_velocity !== null ? objItemData.bod_velocity : '-',
                    modulation: objItemData.found && objItemData.modulation !== null ? objItemData.modulation : '-',
                    snr: objItemData.found && objItemData.snr !== null ? objItemData.snr : '-',
                    mirrors: objItemData.found && objItemData.mirrors !== null ? objItemData.mirrors : '-',
                };
                
                // Add row to table
                table.addRow(rowData);
                
                // Clear input
                this.value = '';
            } catch (error) {
                console.error('Ошибка при обработке данных:', error);
                alert('Произошла ошибка при обработке данных. Проверьте консоль для деталей.');
            } finally {
                // Re-enable input
                this.disabled = false;
                this.focus();
            }
        }
    });
    
    // Export to Excel
    document.getElementById('export-xlsx').addEventListener('click', function() {
        table.download("xlsx", "data_export.xlsx", {sheetName: "Данные"});
    });
    
    // Clear table
    document.getElementById('clear-table').addEventListener('click', function() {
        if (confirm('Вы уверены, что хотите очистить таблицу?')) {
            table.clearData();
            updateRowCount();
        }
    });
    
    // Initialize row count
    updateRowCount();
});
</script>
{% endblock %}
