import * as Cesium from "cesium";

const viewer = new Cesium.Viewer("cesiumContainer", {
  terrain: Cesium.Terrain.fromWorldTerrain(),
  animation: false,
  timeline: false,
});
// Suppress terrain data to avoid clashing with IntegratedMesh layer geometry
viewer.scene.globe.depthTestAgainstTerrain = false;

// More datasets to tour can be added here..
// The url passed to I3SDataProvider supports loading a single Indexed 3D Scene (I3S) layer (.<host>/SceneServer/layers/<id>) or a collection of scene layers (.<host>/SceneServer) from a SceneServer.
const tours = {
  Frankfurt:
    "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/Frankfurt2017_vi3s_18/SceneServer/layers/0",
};
try {
  // Initialize a terrain provider which provides geoid conversion between gravity related (typically I3S datasets) and ellipsoidal based
  // height systems (Cesium World Terrain).
  // If this is not specified, or the URL is invalid no geoid conversion will be applied.
  // The source data used in this transcoding service was compiled from https://earth-info.nga.mil/#tab_wgs84-data and is based on EGM2008 Gravity Model
  const geoidService = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
    "https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/EGM2008/ImageServer",
  );

  // Create i3s options to pass optional parameters useful for debugging and visualizing
  const i3sOptions = {
    geoidTiledTerrainProvider: geoidService, // pass the geoid service
  };

  // Create I3S data provider
  const i3sProvider = await Cesium.I3SDataProvider.fromUrl(
    tours.Frankfurt,
    i3sOptions,
  );

  // Add the i3s layer provider as a primitive data type
  viewer.scene.primitives.add(i3sProvider);

  // Center camera on I3S once it's loaded
  const center = Cesium.Rectangle.center(i3sProvider.extent);
  center.height = 5000.0;
  viewer.camera.setView({
    destination: Cesium.Ellipsoid.WGS84.cartographicToCartesian(center),
  });
} catch (error) {
  console.log(`There was an error creating the I3S Data Provider: ${error}`);
}
