"use strict";

Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyODgxYzJlNi1kNDZiLTQ3ZmQtYmUxYy0yMWI0OGM3NDA5MzAiLCJpZCI6NDczOSwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTU0MTUyMzU0MX0.shj2hM3pvsvcmE_wMb2aBDuk_cKWmFmbolltInGImwU";

// Flag to determine models that will be loaded
// Set to `true` or `false`
const LOAD_DETAILED_BLDG225 = false;

// Global variable
const viewer = new Cesium.Viewer("cesiumGlobeContainer", {
  //   terrainProvider: Cesium.createWorldTerrain(),
});
// viewer.scene.globe.depthTestAgainstTerrain = true;

const loadTiles = function (urlTiles) {
  const tileset = new Cesium.Cesium3DTileset({
    url: urlTiles,
  });
  viewer.scene.primitives.add(tileset);

  tileset.readyPromise.then(function () {
    viewer
      .zoomTo(
        tileset,
        new Cesium.HeadingPitchRange(
          0.0,
          -0.5,
          tileset.boundingSphere.radius / 0.5
        )
      )
      .otherwise(function (err) {
        throw err;
      });
  });
};

// Function for loading 3DTiles only
const loadNonDetailed = function () {
  // Paths to data sources
  const URL_3DTILES = "data_3d/3dtiles/1_full/tileset.json";

  // Tileset without building 225
  loadTiles(URL_3DTILES);
};

// Function for loading 3DTiles + glTF models
const loadDetailed = function () {
  // Paths to data sources
  const URL_3DTILES = "data_3d/3dtiles/2_partial/tileset.json";
  const URL_GLTF = "data_3d/gltf";

  // Tileset without building 225
  loadTiles(URL_3DTILES);

  // Function for loading glTFs
  const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
    Cesium.Cartesian3.fromDegrees(9.083385, 48.881342, 0)
  );

  const gltfLoad = function (gltfId) {
    viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        url: `${URL_GLTF}/${gltfId}.gltf`,
        modelMatrix: modelMatrix,
        scale: 0.0254,
        allowPicking: true,
      })
    );
  };

  // Load Building 225
  gltfLoad("bosch_si225_3");

  // Load sensors in Building 225
  const gltfArray = [
    "sensor_013",
    "sensor_023",
    "sensor_033",
    "sensor_053",
    "sensor_063",
    "sensor_073",
    "sensor_083",
    "sensor_093",
    "sensor_103",
    "sensor_113",
    "sensor_123",
    "sensor_133",
    "sensor_143",
    "sensor_153",
    "sensor_163",
    "sensor_173",
    "sensor_183",
    "sensor_213",
    "sensor_223",
    "sensor_233",
    "sensor_253",
    "sensor_263",
    "sensor_273",
    "sensor_283",
    "sensor_293",
    "sensor_303",
    "sensor_313",
    "sensor_323",
    "sensor_333",
    "sensor_343",
    "sensor_353",
    "sensor_363",
    "sensor_373",
    "sensor_383_v2",
  ];

  gltfArray.forEach((val) => gltfLoad(val));
};

if (!LOAD_DETAILED_BLDG225) {
  // Default case: load only 3dTiles
  loadNonDetailed();
} else {
  // Alternative case: load 3dTiles + glTF
  loadDetailed();
}
