
// https://googlemaps.github.io/js-markerclusterer/classes/MarkerClusterer.html
// add true for noDraw
// bounds : https://stackoverflow.com/questions/19304574/center-set-zoom-of-map-to-cover-all-visible-markers/19304625#19304625


/**
 * return intersection of both arrays : indexes and g_indexes
 */

function filter_selection_indexes(indexes) {
	// if g_indexes empty, just fill it with indexes
	// because it's like intersection of indexes and g_indexes if g_indexes was the list of all markers
	if (g_indexes.length == 0) {
		// deep copy of indexes
		g_indexes = [].concat(indexes);
	}
	else {
		let intersection = [];
		for (let index of indexes) {
			if (g_indexes.indexOf(index) != -1)
				intersection.push(index);
		}
		// if no intersection found, the filter shouldn't be selectable, so this shouldn't happen
		if (intersection.length)
			g_indexes = intersection;
	}
}


/**
 * if zoom_in is true:
 *   zoom to new selection,
 *   even if already visible in current view
 */

function filter_show_only_selection(indexes, zoom_in = false) {

	filter_selection_indexes(indexes);

	let indexes_count = g_indexes.length;
	if (indexes_count === 0)
		return;

	g_marker_cluster.clearMarkers(true);

	let marker = g_markers[0];
	let position = marker.getPosition();
	let current_bounds = g_map.getBounds();
	let bounds = new google.maps.LatLngBounds(position);

	let outside_bounds = false;
	for (let index of g_indexes) {
		marker = g_markers[index];
		position = marker.getPosition();
		if (! current_bounds.contains(position))
			outside_bounds = true;
		bounds.extend(position);

		g_marker_cluster.addMarker(marker, true);
	}
	if (zoom_in || outside_bounds) {
		if (indexes_count === 1) {
			g_map.setCenter(position);
			g_map.setZoom(max_zoom);
		}
		else if (indexes_count > 1)
			g_map.fitBounds(bounds);
	}
	g_marker_cluster.render();

}

function filter_show_all() {
	g_indexes = [];
	g_marker_cluster.addMarkers(g_markers);
	//g_map.fitBounds(g_init_bounds);
	g_map.setCenter(coordinates_default);
	g_map.setZoom(2);
}

