{% extends 'generic/object.html' %}
{% load static %}
{% load helpers %}

{% block title %}{{ object.name }} - Map View{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="mdi mdi-map" aria-hidden="true"></i>
                    Map: {{ object.name }}
                </h5>
                <div class="card-actions">
                    <a href="{{ object.get_absolute_url }}" class="btn btn-outline-secondary btn-sm">
                        <i class="mdi mdi-arrow-left" aria-hidden="true"></i> Back to Segment
                    </a>
                    <a href="{% url 'plugins:cesnet_service_path_plugin:segment_geojson_download' pk=object.pk %}" 
                       class="btn btn-outline-primary btn-sm">
                        <i class="mdi mdi-download" aria-hidden="true"></i> Download GeoJSON
                    </a>
                </div>
            </div>
            <div class="card-body">
                {% if not object.has_path_data and not has_fallback_line %}
                    <div class="alert alert-warning" role="alert">
                        <i class="mdi mdi-alert-circle" aria-hidden="true"></i>
                        This segment does not have path data and sites don't have coordinates.
                    </div>
                {% else %}
                    <!-- Segment info -->
                    <div class="alert alert-info mb-3">
                        <strong>{{ object.provider }}</strong> | 
                        <span class="badge text-bg-{{ object.get_status_color }}">{{ object.get_status_display }}</span> | 
                        {% if object.path_length_km %}{{ object.path_length_km }} km{% else %}Length unknown{% endif %} | 
                        {{ object.site_a }} ↔ {{ object.site_b }}
                        {% if has_fallback_line %}
                            <br><small class="text-muted">
                                <i class="mdi mdi-information"></i> 
                                No path data available - showing straight line between sites
                            </small>
                        {% endif %}
                    </div>
                    
                    <!-- Map controls -->
                    <div class="mb-3">
                        <button id="fitBounds" class="btn btn-sm btn-outline-primary">
                            <i class="mdi mdi-fit-to-page-outline"></i> Fit to Path
                        </button>
                        <!-- Use the new layer dropdown -->
                        {% include './inc/map_layer_dropdown.html' %}
                    </div>
                    
                    <!-- Map container -->
                    <div id="map" style="height: 600px; width: 100%; border: 1px solid #ddd; border-radius: 4px;"></div>
                    
                    <!-- Load Leaflet -->
                    {% include './inc/leaflet_includes.html' %}

                    <!-- Template data as JSON -->
                    <script type="application/json" id="segment-data">
                    {
                        "siteAData": {{ site_a_data_json|safe }},
                        "siteBData": {{ site_b_data_json|safe }},
                        "segmentStyle": {{ segment_style_json|safe }},
                        "hasFallbackLine": {{ has_fallback_line|yesno:"true,false" }},
                        "hasPathData": {{ object.has_path_data|yesno:"true,false" }},
                        "segmentInfo": {
                            "name": "{{ object.name|escapejs }}",
                            "provider": "{{ object.provider|escapejs }}",
                            "status": "{{ object.get_status_display|escapejs }}",
                            "length": "{% if object.path_length_km %}{{ object.path_length_km }} km{% else %}Length unknown{% endif %}",
                            "route": "{{ object.site_a|escapejs }} ↔ {{ object.site_b|escapejs }}"
                        },
                        "apiUrl": "{% url 'plugins:cesnet_service_path_plugin:segment_geojson_api' pk=object.pk %}"
                    }
                    </script>

                    <!-- Include common layer configuration -->
                    {% include './inc/map_layers_config.html' %}

                    <script>
                    // Parse template data
                    const templateData = JSON.parse(document.getElementById('segment-data').textContent);
                    const siteAData = templateData.siteAData;
                    const siteBData = templateData.siteBData;
                    const segmentStyle = templateData.segmentStyle;
                    const hasFallbackLine = templateData.hasFallbackLine;
                    const hasPathData = templateData.hasPathData;
                    const segmentInfo = templateData.segmentInfo;
                    const apiUrl = templateData.apiUrl;
                    
                    // Create map
                    const map = L.map('map').setView([49.75, 15.5], 7);
                    
                    // Initialize layers using common function
                    initializeMapLayers(map);
                    
                    // Store layers for bounds fitting
                    const allLayers = [];
                    
                    // Function to add site markers
                    function addSiteMarkers() {
                        if (siteAData) {
                            const markerA = L.circleMarker([siteAData.lat, siteAData.lng], {
                                radius: 8,
                                fillColor: '#007bff',
                                color: '#ffffff',
                                weight: 2,
                                opacity: 1,
                                fillOpacity: 0.8
                            }).addTo(map);
                            
                            markerA.bindPopup(
                                '<div>' +
                                '<h6>Site A: ' + siteAData.name + '</h6>' +
                                '<p><strong>Coordinates:</strong> ' + siteAData.lat.toFixed(6) + ', ' + siteAData.lng.toFixed(6) + '</p>' +
                                '</div>'
                            );
                            
                            allLayers.push(markerA);
                        }
                        
                        if (siteBData) {
                            const markerB = L.circleMarker([siteBData.lat, siteBData.lng], {
                                radius: 8,
                                fillColor: '#28a745',
                                color: '#ffffff',
                                weight: 2,
                                opacity: 1,
                                fillOpacity: 0.8
                            }).addTo(map);
                            
                            markerB.bindPopup(
                                '<div>' +
                                '<h6>Site B: ' + siteBData.name + '</h6>' +
                                '<p><strong>Coordinates:</strong> ' + siteBData.lat.toFixed(6) + ', ' + siteBData.lng.toFixed(6) + '</p>' +
                                '</div>'
                            );
                            
                            allLayers.push(markerB);
                        }
                    }
                    
                    // Function to add fallback line
                    function addFallbackLine() {
                        if (hasFallbackLine && siteAData && siteBData) {
                            const lineCoordinates = [
                                [siteAData.lat, siteAData.lng],
                                [siteBData.lat, siteBData.lng]
                            ];
                            
                            const fallbackLine = L.polyline(lineCoordinates, {
                                color: segmentStyle.color,
                                weight: segmentStyle.weight,
                                opacity: segmentStyle.opacity,
                                dashArray: '5, 10' // Dashed to indicate it's not actual path
                            }).addTo(map);
                            
                            fallbackLine.bindPopup(
                                '<div>' +
                                '<h6>' + segmentInfo.name + '</h6>' +
                                '<p><strong>Provider:</strong> ' + segmentInfo.provider + '</p>' +
                                '<p><strong>Status:</strong> ' + segmentInfo.status + '</p>' +
                                '<p><strong>Length:</strong> ' + segmentInfo.length + '</p>' +
                                '<p><strong>Route:</strong> ' + segmentInfo.route + '</p>' +
                                '<p><small class="text-muted">Note: Straight line - actual path data not available</small></p>' +
                                '</div>'
                            );
                            
                            allLayers.push(fallbackLine);
                        }
                    }
                    
                    // Function to fit map to all layers
                    function fitMapToLayers() {
                        if (allLayers.length > 0) {
                            const group = new L.featureGroup(allLayers);
                            map.fitBounds(group.getBounds(), {padding: [20, 20]});
                        }
                    }
                    
                    // Add site markers first
                    addSiteMarkers();
                    
                    if (hasPathData) {
                        // Load segment path if available
                        fetch(apiUrl)
                            .then(response => response.json())
                            .then(data => {
                                if (data.features && data.features.length > 0) {
                                    // Add to map with updated styling
                                    const pathLayer = L.geoJSON(data, {
                                        style: {
                                            color: segmentStyle.color,
                                            weight: segmentStyle.weight,
                                            opacity: segmentStyle.opacity,
                                            dashArray: segmentStyle.dashArray || null
                                        }
                                    }).addTo(map);
                                    
                                    pathLayer.bindPopup(
                                        '<div>' +
                                        '<h6>' + segmentInfo.name + '</h6>' +
                                        '<p><strong>Provider:</strong> ' + segmentInfo.provider + '</p>' +
                                        '<p><strong>Status:</strong> ' + segmentInfo.status + '</p>' +
                                        '<p><strong>Length:</strong> ' + segmentInfo.length + '</p>' +
                                        '<p><strong>Route:</strong> ' + segmentInfo.route + '</p>' +
                                        '</div>'
                                    );
                                    
                                    allLayers.push(pathLayer);
                                    
                                    // Fit to all layers
                                    setTimeout(fitMapToLayers, 100);
                                } else {
                                    console.log('No path features found');
                                    // If no path data, add fallback line and fit to sites
                                    addFallbackLine();
                                    setTimeout(fitMapToLayers, 100);
                                }
                            })
                            .catch(error => {
                                console.error('Error loading path:', error);
                                // On error, add fallback line if possible
                                addFallbackLine();
                                setTimeout(fitMapToLayers, 100);
                            });
                    } else {
                        // No path data available, add fallback line and fit to sites
                        addFallbackLine();
                        setTimeout(fitMapToLayers, 100);
                    }
                    
                    // Control handlers
                    document.getElementById('fitBounds').onclick = function() {
                        fitMapToLayers();
                    };
                    
                    // Initialize layer switching functionality
                    initializeLayerSwitching(map);
                    </script>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}