import Deferred from "@/sdk/utils/Deferred";
import Emiter from "@/sdk/utils/Emiter";

export default class Scene extends Emiter {
  constructor(app) {
    super();
    this.locked = null;
    this.app = app;
  }

  /**
   * 停止加载资源
   */

  lock() {
    this.locked = Deferred();
  }

  /**
   * 恢复加载资源
   */
  unlock() {
    if (this.locked) {
      this.locked.resolve();
      this.locked = null;
    }
  }

  sceneReady() {
    this.emit("sceneReady");
  }

  async start() {
    window.onPanoReady = () => {
      if (!this.app.krpanoDom) {
        this.app.krpanoDom = document.getElementById("krpanoSWFObject");
      }
      this.emit("ready");
    };

    window.onPanoViewChanged = () => {
      this.emit("viewChanged");
    };

    window.onNewPano = () => {
      this.emit("onNewPano");
    };

    window.onExitVrStatus = () => {
      this.emit("onExitVr");
    };

    let settings = {
      "events[skin_events].onloadcomplete": "js(window.onPanoReady());",
      "events[skin_events].onviewchanged": "js(window.onPanoViewChanged());",
      "events[skin_events].onnewpano": "js(window.onNewPano());",
      // "plugin[WebVR].onexitvr": "js(window.onExitVrStatus());",
    };
    if (this.locked) {
      await this.locked;
    }

    if (this.app.options.isHavePano) {
      // debugger;
      embedpano({
        ...this.app.options,
        vars: {
          ...this.app.options.vars,
          ...settings,
        },

        onready: (pano) => {
          console.log("pano", pano);
          this.emit("ready");
        },
        onerror: function (error) {
          debugger;
          console.error("error", error);
        },
      });
    } else {
      this.emit("ready");
    }
  }
}
