var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import { MarkerClusterer } from '@googlemaps/markerclusterer';
import { useMap } from '@vis.gl/react-google-maps';
import { omit, prop } from 'ramda';
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { EntityMarker } from '../EntityMarker';
import { CustomClusterRenderer } from './CustomClusterRenderer';
export var ClusteredMarkers = memo(function (_a) {
    var entityMarkers = _a.entityMarkers, options = _a.options, enabledClustering = _a.enabledClustering, onMarkerClick = _a.onMarkerClick;
    var _b = useState({}), markers = _b[0], setMarkers = _b[1];
    var map = useMap();
    var clusterer = useMemo(function () {
        if (!enabledClustering || !map)
            return null;
        return new MarkerClusterer({
            map: map,
            renderer: new CustomClusterRenderer(options),
            algorithmOptions: { maxZoom: options === null || options === void 0 ? void 0 : options.maxZoom }
        });
    }, [map, options, enabledClustering]);
    useEffect(function () {
        return function () {
            clusterer === null || clusterer === void 0 ? void 0 : clusterer.onRemove();
        };
    }, [entityMarkers]);
    useEffect(function () {
        if (!clusterer)
            return;
        clusterer.clearMarkers();
        clusterer.addMarkers(Object.values(markers));
    }, [clusterer, markers]);
    var setMarkerRef = useCallback(function (marker, key) {
        setMarkers(function (markers) {
            var _a;
            if (marker && !markers[key]) {
                return __assign(__assign({}, markers), (_a = {}, _a[key] = marker, _a));
            }
            else if (!marker && markers[key]) {
                return omit([key], markers);
            }
            else {
                return markers;
            }
        });
    }, []);
    return (React.createElement(React.Fragment, null, entityMarkers.filter(prop('point')).map(function (marker) { return (React.createElement(EntityMarker, { key: marker.id, marker: marker, clusterer: enabledClustering ? setMarkerRef : undefined, onClick: onMarkerClick })); })));
});
ClusteredMarkers.displayName = 'ClusteredMarkers';
