import { ThreejsLayer } from "../layers/Threejs";
import { BuildingsLayer } from "../layers/Buildings";
export class MapboxViewerLayersController {
  constructor(_viewer) {
    this._viewer = _viewer;
  }
  addLayers() {
    if (!this._viewer.mapLoaded()) {
      console.warn("map not loaded");
      return;
    }
    const map = this._viewer.map();
    if (!map) {
      console.warn("no map found");
      return;
    }
    const current_style = map.getStyle();
    const layers = current_style.layers;
    if (!layers) {
      console.warn("no layers found");
      return;
    }
    let label_layer_id = null;
    for (let layer of layers) {
      if (layer.type == "symbol" && layer.layout["text-field"]) {
        label_layer_id = layer.id;
      }
    }
    const cameraNode = this._viewer.cameraNode();
    if (label_layer_id != null) {
      this._addLayerBuildings(map, label_layer_id, cameraNode);
      this._addLayerThreejs(map, label_layer_id);
    }
    this._addLayer3D(map, cameraNode);
    this._addLayerSky(map, cameraNode);
  }
  resize() {
    if (this._threejsLayer) {
      this._threejsLayer.resize();
    }
  }
  _addLayer3D(map, cameraNode) {
    if (!cameraNode.pv.tlayer3D) {
      return;
    }
    map.addSource("mapbox-dem", {
      type: "raster-dem",
      url: "mapbox://mapbox.mapbox-terrain-dem-v1",
      tileSize: 512,
      maxzoom: 14
    });
    map.setTerrain({ source: "mapbox-dem", exaggeration: 1.5 });
  }
  _addLayerSky(map, cameraNode) {
    if (!cameraNode.pv.tlayerSky) {
      return;
    }
    map.addLayer({
      id: "sky",
      type: "sky",
      paint: {
        "sky-type": "atmosphere",
        "sky-atmosphere-sun": [0, 0],
        "sky-atmosphere-sun-intensity": 15
      }
    });
  }
  _addLayerBuildings(map, label_layer_id, cameraNode) {
    if (!map) {
      return;
    }
    if (!cameraNode.pv.tlayerBuildings) {
      return;
    }
    if (this._has_layer_id(BuildingsLayer.id)) {
      return;
    }
    map.addLayer(BuildingsLayer, label_layer_id);
  }
  _addLayerThreejs(map, label_layer_id) {
    if (!map) {
      return;
    }
    const camera_node = this._viewer.cameraNode();
    if (!camera_node) {
      console.log("no camera_node found");
      return;
    }
    this._threejsLayer = new ThreejsLayer(camera_node, camera_node.scene().threejsScene(), this._viewer);
    map.addLayer(this._threejsLayer, label_layer_id);
  }
  _has_layer_id(layer_id) {
    var _a;
    const map = this._viewer.map();
    if (map) {
      const current_style = map.getStyle();
      const layer_ids = ((_a = current_style.layers) == null ? void 0 : _a.map((l) => l.id)) || [];
      return layer_ids.includes(layer_id);
    }
    return false;
  }
}
