<script setup>
import { GeoJSONSource, ImageSource, Map, RasterTileSource } from "mapbox-gl";
import { inject, onUnmounted, watch, useMapbox, computed, useMapboxInstance, triggerRef, _useMapboxInstances } from "#imports";
const props = defineProps({
  sourceId: { type: String, required: true },
  source: { type: Object, required: true }
});
const mapId = inject("MapID");
if (!mapId) throw "Mapbox Source must be placed inside a Map component";
const mapRef = useMapboxInstance(mapId);
const sourceExists = computed(() => {
  return !!mapRef.value?.getSource(props.sourceId);
});
const mapbox_instances = _useMapboxInstances();
useMapbox(mapId, (map) => {
  function addSource() {
    if (!sourceExists.value) {
      map?.addSource(props.sourceId, props.source);
    }
  }
  addSource();
  map.on("style.load", () => {
    addSource();
  });
});
onUnmounted(() => {
  mapRef.value?.removeSource(props.sourceId);
});
watch(() => props.source, () => {
  const source = mapRef.value?.getSource(props.sourceId);
  if (!source) return;
  props.source.type === "geojson";
  if (props.source.type === "geojson" && props.source.data) {
    source.setData(props.source.data);
  }
  if (props.source.type === "vector" && (props.source.tiles || props.source.url)) {
    if (props.source.tiles) {
      source.setTiles(props.source.tiles);
    }
    if (props.source.url) {
      source.setUrl(props.source.url);
    }
    source.reload();
  }
  if (props.source.type === "image" && props.source.url) {
    source.updateImage(props.source);
  }
  if (props.source.type === "raster" && (props.source.url || props.source.tiles)) {
    if (props.source.url) {
      source.setUrl(props.source.url);
    }
    if (props.source.tiles) {
      source.setTiles(props.source.tiles);
    }
    source.reload();
  }
});
</script>

<template>
  <div>
    <slot />
  </div>
</template>
