import TilesetOptions from "./3DTilesetOptions";

export default {
  props: { ...TilesetOptions },
  inject: ["Cesium", "webGlobe"],
  created() {
    this.tileset = this.createCesiumObject();
    this.mount();
    // this.watchProp();
  },
  destroyed() {
    this.unmount();
  },
  methods: {
    createCesiumObject() {
      const { $props } = this;
      return new Cesium.Cesium3DTileset($props);
    },
    watchProp() {
      let { show } = this;
      if (show) {
        this.$watch("show", function(next) {
          if (this.initial) return;
          this.tileset.show = next;
        });
      }
    },
    mount() {
      const { webGlobe, tileset } = this;
      const viewer = webGlobe.viewer;
      if (viewer.isDestroyed()) return;

      tileset.readyPromise
        .then(function(primitives) {
          viewer.scene.primitives.add(primitives);
          viewer.zoomTo(
            primitives,
            new Cesium.HeadingPitchRange(
              0.0,
              -0.5,
              primitives.boundingSphere.radius * 2.0
            )
          );
        })
        .otherwise(function(error) {
          console.error("3dtileset", error);
        });
    },
    unmount() {
      const { webGlobe, tileset } = this;
      const viewer = webGlobe.viewer;
      return !viewer.isDestroyed() && viewer.scene.primitives.remove(tileset);
    }
  },
  render(createElement) {
    return createElement("span");
  }
};
