import mapboxgl from "mapbox-gl";
import { TypedViewer } from "@polygonjs/polygonjs/dist/src/engine/viewers/_Base";
import { MapboxViewerEventsController } from "./utils/controllers/Event";
import { MapboxViewerStylesheetController } from "./utils/controllers/Stylesheet";
import { MapboxViewerLayersController } from "./utils/controllers/Layers";
import { MapsRegister } from "../../core/mapbox/MapsRegister";
const CSS_CLASS = "CoreMapboxViewer";
export class MapboxViewer extends TypedViewer {
  constructor(_cameraNode) {
    super(_cameraNode);
    this._cameraNode = _cameraNode;
    this._mapLoaded = false;
    this.layers_controller = new MapboxViewerLayersController(this);
    this.mapbox_events_controller = new MapboxViewerEventsController(this);
    this._canvasContainer = document.createElement("div");
    this._canvasContainer.id = `mapbox_container_id_${Math.random()}`.replace(".", "_");
    this._canvasContainer.style.height = "100%";
    MapboxViewerStylesheetController.load();
    this._map = this._cameraNode.createMap(this._canvasContainer);
  }
  async mount(element) {
    var _a, _b;
    super.mount(element);
    (_a = this._domElement) == null ? void 0 : _a.appendChild(this._canvasContainer);
    (_b = this._domElement) == null ? void 0 : _b.classList.add(CSS_CLASS);
    this.mapbox_events_controller.init_events();
    this._map.on("load", () => {
      if (this._map) {
        this._mapLoaded = true;
        this._canvas = this._findCanvas();
        this.eventsController().init();
        MapsRegister.instance().registerMap(this._canvasContainer.id, this._map);
        this.layers_controller.addLayers();
        this.mapbox_events_controller.camera_node_move_end();
        window.dispatchEvent(new Event("resize"));
      }
    });
  }
  mapLoaded() {
    return this._mapLoaded;
  }
  map() {
    return this._map;
  }
  canvasContainer() {
    return this._canvasContainer;
  }
  onResize() {
    if (this._map) {
      this._map.resize();
    }
    this.layers_controller.resize();
    this.mapbox_events_controller.camera_node_move_end();
  }
  dispose() {
    var _a;
    MapsRegister.instance().deregisterMap(this._canvasContainer.id);
    (_a = this._cameraNode) == null ? void 0 : _a.removeMap(this._canvasContainer);
    super.dispose();
  }
  waitForMapLoaded() {
    if (this._map.loaded()) {
      return;
    } else {
      return new Promise((resolve, reject) => {
        if (this._map) {
          this._map.on("load", () => {
            resolve(void 0);
          });
        }
      });
    }
  }
  cameraLngLat() {
    var _a;
    return (_a = this._cameraNode) == null ? void 0 : _a.lngLat();
  }
  _addNavigationControls() {
    var _a;
    const nav = new mapboxgl.NavigationControl();
    (_a = this._map) == null ? void 0 : _a.addControl(nav, "bottom-right");
  }
  _findCanvas() {
    return this._canvasContainer.getElementsByTagName("canvas")[0];
  }
}
