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

{% block title %}Список объектов{% endblock %}

{% block content %}
<div class="container-fluid px-3">
    <div class="row mb-3">
        <div class="col-12">
            <h2>Список объектов</h2>
        </div>
    </div>
    
    <!-- Toolbar -->
    <div class="row mb-3">
        <div class="col-12">
            <div class="card">
                <div class="card-body">
                    <div class="d-flex flex-wrap align-items-center gap-3">
                        <div style="min-width: 300px; flex-grow: 1;">
                            <label for="toolbar-search" class="form-label mb-0">Поиск:</label>
                            <input type="text" id="toolbar-search" class="form-control" placeholder="Поиск по имени, местоположению..." value="{{ search_query|default:'' }}">
                        </div>
                        <div class="ms-auto">
                            <button type="button" class="btn btn-outline-primary" onclick="performSearch()">Найти</button>
                            <button type="button" class="btn btn-outline-secondary" onclick="clearSearch()">Очистить</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row g-3">
        <!-- Filters Sidebar - Made narrower -->
        <div class="col-md-2">
            <div class="card h-100">
                <div class="card-body">
                    <h5 class="card-title">Фильтры</h5>
                    <form method="get" id="filter-form">
                        <!-- Satellite Selection - Multi-select -->
                        <div class="mb-2">
                            <label class="form-label">Спутник:</label>
                            <div class="d-flex justify-content-between mb-1">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('satellite_id', true)">Выбрать</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('satellite_id', false)">Снять</button>
                            </div>
                            <select name="satellite_id" class="form-select form-select-sm mb-2" multiple size="4">
                                {% for satellite in satellites %}
                                    <option value="{{ satellite.id }}" 
                                        {% if satellite.id in selected_satellites %}selected{% endif %}>
                                        {{ satellite.name }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <!-- Frequency Filter -->
                        <div class="mb-2">
                            <label class="form-label">Частота, МГц:</label>
                            <input type="number" step="0.001" name="freq_min" class="form-control form-control-sm mb-1" placeholder="От" value="{{ freq_min|default:'' }}">
                            <input type="number" step="0.001" name="freq_max" class="form-control form-control-sm" placeholder="До" value="{{ freq_max|default:'' }}">
                        </div>
                        
                        <!-- Range Filter -->
                        <div class="mb-2">
                            <label class="form-label">Полоса, МГц:</label>
                            <input type="number" step="0.001" name="range_min" class="form-control form-control-sm mb-1" placeholder="От" value="{{ range_min|default:'' }}">
                            <input type="number" step="0.001" name="range_max" class="form-control form-control-sm" placeholder="До" value="{{ range_max|default:'' }}">
                        </div>
                        
                        <!-- SNR Filter -->
                        <div class="mb-2">
                            <label class="form-label">ОСШ:</label>
                            <input type="number" step="0.001" name="snr_min" class="form-control form-control-sm mb-1" placeholder="От" value="{{ snr_min|default:'' }}">
                            <input type="number" step="0.001" name="snr_max" class="form-control form-control-sm" placeholder="До" value="{{ snr_max|default:'' }}">
                        </div>
                        
                        <!-- Symbol Rate Filter -->
                        <div class="mb-2">
                            <label class="form-label">Сим. v, БОД:</label>
                            <input type="number" step="0.001" name="bod_min" class="form-control form-control-sm mb-1" placeholder="От" value="{{ bod_min|default:'' }}">
                            <input type="number" step="0.001" name="bod_max" class="form-control form-control-sm" placeholder="До" value="{{ bod_max|default:'' }}">
                        </div>
                        
                        <!-- Removed old search input as it's now in the toolbar -->
                        
                        <!-- Modulation Filter -->
                        <div class="mb-2">
                            <label class="form-label">Модуляция:</label>
                            <div class="d-flex justify-content-between mb-1">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('modulation', true)">Выбрать</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('modulation', false)">Снять</button>
                            </div>
                            <select name="modulation" class="form-select form-select-sm mb-2" multiple size="4">
                                {% for mod in modulations %}
                                    <option value="{{ mod.id }}" 
                                        {% if mod.id in selected_modulations %}selected{% endif %}>
                                        {{ mod.name }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <!-- Polarization Filter -->
                        <div class="mb-2">
                            <label class="form-label">Поляризация:</label>
                            <div class="d-flex justify-content-between mb-1">
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('polarization', true)">Выбрать</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="selectAllOptions('polarization', false)">Снять</button>
                            </div>
                            <select name="polarization" class="form-select form-select-sm mb-2" multiple size="4">
                                {% for pol in polarizations %}
                                    <option value="{{ pol.id }}" 
                                        {% if pol.id in selected_polarizations %}selected{% endif %}>
                                        {{ pol.name }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <!-- Kubsat Coordinates Filter -->
                        <div class="mb-2">
                            <label class="form-label">Координаты Кубсата:</label>
                            <div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="has_kupsat" id="has_kupsat_1" value="1" 
                                        {% if has_kupsat == '1' %}checked{% endif %}>
                                    <label class="form-check-label" for="has_kupsat_1">Есть</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="has_kupsat" id="has_kupsat_0" value="0" 
                                        {% if has_kupsat == '0' %}checked{% endif %}>
                                    <label class="form-check-label" for="has_kupsat_0">Нет</label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Valid Coordinates Filter -->
                        <div class="mb-2">
                            <label class="form-label">Координаты опер. отдела:</label>
                            <div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="has_valid" id="has_valid_1" value="1" 
                                        {% if has_valid == '1' %}checked{% endif %}>
                                    <label class="form-check-label" for="has_valid_1">Есть</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input" type="checkbox" name="has_valid" id="has_valid_0" value="0" 
                                        {% if has_valid == '0' %}checked{% endif %}>
                                    <label class="form-check-label" for="has_valid_0">Нет</label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Items Per Page -->
                        <div class="mb-2">
                            <label for="items-per-page" class="form-label">Элементов:</label>
                            <select name="items_per_page" id="items-per-page" class="form-select form-select-sm" onchange="document.getElementById('filter-form').submit();">
                                {% for option in available_items_per_page %}
                                    <option value="{{ option }}" {% if option == items_per_page %}selected{% endif %}>
                                        {{ option }}
                                    </option>
                                {% endfor %}
                            </select>
                        </div>
                        
                        <!-- Apply Filters and Reset Buttons -->
                        <div class="d-grid gap-2 mt-2">
                            <button type="submit" class="btn btn-primary btn-sm">Применить</button>
                            <a href="?" class="btn btn-secondary btn-sm">Сбросить</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Main Table -->
        <div class="col-md-10">
            <div class="card h-100">
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 75vh; overflow-y: auto;">
                        <table class="table table-striped table-hover table-sm" style="font-size: 0.85rem;">
                            <thead class="table-dark sticky-top">
                                <tr>
                                    <th scope="col" class="text-center" style="width: 3%;">
                                        <input type="checkbox" id="select-all" class="form-check-input">
                                    </th>
                                    <th scope="col">Имя</th>
                                    <th scope="col">Спутник</th>
                                    <th scope="col">Част, МГц</th>
                                    <th scope="col">Полоса, МГц</th>
                                    <th scope="col">Поляр</th>
                                    <th scope="col">Сим. v</th>
                                    <th scope="col">Модул</th>
                                    <th scope="col">ОСШ</th>
                                    <th scope="col">Геолокация</th>
                                    <th scope="col">Кубсат</th>
                                    <th scope="col">Опер. отд</th>
                                    <th scope="col">Гео-куб, км</th>
                                    <th scope="col">Гео-опер, км</th>
                                    <th scope="col">Куб-опер, км</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for item in processed_objects %}
                                    <tr>
                                        <td class="text-center">
                                            <input type="checkbox" class="form-check-input item-checkbox" value="{{ item.id }}">
                                        </td>
                                        <td>{{ item.name }}</td>
                                        <td>{{ item.satellite_name }}</td>
                                        <td>{{ item.frequency }}</td>
                                        <td>{{ item.freq_range }}</td>
                                        <td>{{ item.polarization }}</td>
                                        <td>{{ item.bod_velocity }}</td>
                                        <td>{{ item.modulation }}</td>
                                        <td>{{ item.snr }}</td>
                                        <td>{{ item.geo_coords }}</td>
                                        <td>{{ item.kupsat_coords }}</td>
                                        <td>{{ item.valid_coords }}</td>
                                        <td>{{ item.distance_geo_kup }}</td>
                                        <td>{{ item.distance_geo_valid }}</td>
                                        <td>{{ item.distance_kup_valid }}</td>
                                    </tr>
                                {% empty %}
                                    <tr>
                                        <td colspan="15" class="text-center py-4">
                                            {% if selected_satellite_id %}
                                                Нет данных для выбранных фильтров
                                            {% else %}
                                                Пожалуйста, выберите спутник для отображения данных
                                            {% endif %}
                                        </td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    {% if page_obj.paginator.num_pages > 1 %}
                        <nav aria-label="Page navigation" class="px-3 pb-3">
                            <ul class="pagination justify-content-center">
                                {% if page_obj.has_previous %}
                                    <li class="page-item">
                                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page=1">Первая</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">Предыдущая</a>
                                    </li>
                                {% endif %}
                                
                                {% for num in page_obj.paginator.page_range %}
                                    {% if page_obj.number == num %}
                                        <li class="page-item active">
                                            <span class="page-link">{{ num }}</span>
                                        </li>
                                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                        <li class="page-item">
                                            <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                                        </li>
                                    {% endif %}
                                {% endfor %}
                                
                                {% if page_obj.has_next %}
                                    <li class="page-item">
                                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">Следующая</a>
                                    </li>
                                    <li class="page-item">
                                        <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.paginator.num_pages }}">Последняя</a>
                                    </li>
                                {% endif %}
                            </ul>
                        </nav>
                    {% endif %}
                    
                    <!-- Pagination Info -->
                    {% if page_obj %}
                        <div class="px-3 pb-3 d-flex justify-content-between align-items-center">
                            <div>Показано {{ page_obj.start_index }}-{{ page_obj.end_index }} из {{ page_obj.paginator.count }} записей</div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript for checkbox functionality and filters -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Select/Deselect all checkboxes
    const selectAllCheckbox = document.getElementById('select-all');
    const itemCheckboxes = document.querySelectorAll('.item-checkbox');
    
    if (selectAllCheckbox && itemCheckboxes.length > 0) {
        selectAllCheckbox.addEventListener('change', function() {
            itemCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
        });
        
        // Update select all checkbox state based on individual selections
        itemCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = Array.from(itemCheckboxes).every(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
            });
        });
    }
    
    // Handle multiple selection for modulations and polarizations
    const modulationSelect = document.querySelector('select[name="modulation"]');
    const polarizationSelect = document.querySelector('select[name="polarization"]');
    
    // Prevent deselecting all options when Ctrl+click is used
    if (modulationSelect) {
        modulationSelect.addEventListener('change', function(e) {
            document.getElementById('filter-form').submit();
        });
    }
    
    if (polarizationSelect) {
        polarizationSelect.addEventListener('change', function(e) {
            document.getElementById('filter-form').submit();
        });
    }
    
    // Handle kubsat and valid coords checkboxes (mutually exclusive)
    // Add a function to handle radio-like behavior for these checkboxes
    function setupRadioLikeCheckboxes(name) {
        const checkboxes = document.querySelectorAll(`input[name="${name}"]`);
        checkboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                // If this checkbox is checked, uncheck the other
                if (this.checked) {
                    checkboxes.forEach(other => {
                        if (other !== this) {
                            other.checked = false;
                        }
                    });
                } else {
                    // If both are unchecked, no action needed
                }
                document.getElementById('filter-form').submit();
            });
        });
    }
    
    setupRadioLikeCheckboxes('has_kupsat');
    setupRadioLikeCheckboxes('has_valid');
    
    // Function to select/deselect all options in a select element
    window.selectAllOptions = function(selectName, selectAll) {
        const selectElement = document.querySelector(`select[name="${selectName}"]`);
        if (selectElement) {
            for (let i = 0; i < selectElement.options.length; i++) {
                selectElement.options[i].selected = selectAll;
            }
            document.getElementById('filter-form').submit();
        }
    };
    
    // Function to update the page when satellite selection changes
    function updateSatelliteSelection() {
        document.getElementById('filter-form').submit();
    }
    
    // Get all current filter values and return as URL parameters
    function getAllFilterParams() {
        const form = document.getElementById('filter-form');
        const searchValue = document.getElementById('toolbar-search').value;
        
        // Create URLSearchParams object from the form
        const params = new URLSearchParams(new FormData(form));
        
        // Add search value from toolbar if present
        if (searchValue.trim() !== '') {
            params.set('search', searchValue);
        } else {
            // Remove search parameter if empty
            params.delete('search');
        }
        
        return params.toString();
    }
    
    // Function to perform search
    window.performSearch = function() {
        const filterParams = getAllFilterParams();
        window.location.search = filterParams;
    };
    
    // Function to clear search
    window.clearSearch = function() {
        // Clear only the search input in the toolbar
        document.getElementById('toolbar-search').value = '';
        // Submit the form to update the results
        const filterParams = getAllFilterParams();
        window.location.search = filterParams;
    };
    
    // Handle Enter key in toolbar search
    const toolbarSearch = document.getElementById('toolbar-search');
    if (toolbarSearch) {
        toolbarSearch.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }
    
    // Add event listener to satellite select for immediate update
    const satelliteSelect = document.querySelector('select[name="satellite_id"]');
    if (satelliteSelect) {
        satelliteSelect.addEventListener('change', function() {
            updateSatelliteSelection();
        });
    }
});
</script>
{% endblock %}