<div class="{{ partial_item.grid_columns }} columns">
    <style>
        /* */
        .map-popup {
            background-color: white;
            border-radius: 6px;
            border: 1px solid #eee;
            padding: 5px;
        }
        .map-popup:hover {
            background: #F7F7F5;
            cursor: pointer;   
        }
        .map-popup > p {
            margin-bottom: 0;
        }
    </style>
    <h4 class="map-partial partial-heading">
            {{ partial_item.title }}
    </h4>
    <div class="map-partial partial" id="{{ partial_item.name }}" style="overflow: scroll; height:{{ partial_item.grid_rows * 50}}px;">
            <div class="map-popup" id="{{ partial_item.name }}_popup"></div>
    </div>
</div>

<script type="text/javascript">
    $(function () {

        var streamConfig = {
            table_name: {{ partial_item.table_name|tojson|safe }},
            key_field: {{ partial_item.key_field|tojson|safe }},
            restrict_by: {{ partial_item.restrict_by|tojson|safe }},
            start_key: {{ partial_item.start_key|tojson|safe }},
            start_item_number: {{ partial_item.start_item_number|tojson|safe }},
            count: {{ partial_item.count|tojson|safe }},
            end_key: {{ partial_item.end_key|tojson|safe }},
            stream_tag: {{ partial_item.stream_tag|tojson|safe }}
        };

        var record_link = "{{ partial_item.record_link }}";
        
        var headers = {{ partial_item.popup|tojson|safe }};

        var vectorSource = new ol.source.Vector({
            features: []
        });
        
        var vectorLayer = new ol.layer.Vector({
            source: vectorSource
        });

        var map = new ol.Map({
            target: '{{ partial_item.name }}',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                }),
                vectorLayer
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat({{ partial_item.center|tojson|safe }}),
                zoom: {{ partial_item.zoom|tojson|safe }}
            })
        });

        var popupElement = document.getElementById("{{ partial_item.name }}_popup");

        var popup = new ol.Overlay({
            element: popupElement,
            positioning: 'bottom-center',
            stopEvent: false,
            offset: [0, -10]
        });

        map.addOverlay(popup);

        // display popup on click
        map.on('click', function(evt) {
            var feature = map.forEachFeatureAtPixel(evt.pixel,
                function(feature) {
                    return feature;
                });
            if (feature) {
                var coordinates = feature.getGeometry().getCoordinates();
                popup.setPosition(coordinates);
                var vals = feature.get('vals');
                var innerHTML = "<a href=" + window.format(record_link, vals) +">";
                
                headers.forEach( (header) => {
                    if(header in vals) {
                        innerHTML += header + " : " + vals[header] + "<br> <br>" ;                        
                    }
                });
                innerHTML += "</a>";
                popupElement.innerHTML = innerHTML;
                $(popupElement).show();
            } else {
                popupElement.innerHTML = "";
                $(popupElement).hide();
            }
        });

        // change mouse cursor when over marker
        map.on('pointermove', function(e) {
            if (e.dragging) {
                popupElement.innerHTML = "";
                $(popupElement).hide();
                return;
            }
            var pixel = map.getEventPixel(e.originalEvent);
            var hit = map.hasFeatureAtPixel(pixel);
            // map.getTarget().style.cursor = hit ? 'pointer' : '';
        });


        var mapStream = new Stream(socket, streamConfig, (data) => {
            console.log(mapStream.cache);
            vectorSource.clear()
            mapStream.cache.forEach((item) => {
                var iconFeature = new ol.Feature(
                        {
                            geometry: new ol.geom.Point(ol.proj.fromLonLat([item.gps_lon, item.gps_lat])),
                            id: item.key,
                            vals: item
                        }
                );
                var iconStyle = new ol.style.Style({
                        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
                        src: 'https://openlayers.org/en/v4.6.5/examples/data/dot.png'
                        }))
                });
                iconFeature.setStyle(iconStyle);
                vectorSource.addFeature(iconFeature);

            });
        });
        mapStream.startStream();
    });
</script>