cc.Class({
  extends: cc.Component,

  properties: {},

  onLoad() {
    const { setAdapters } = globalThis.Play;
    if (cc.sys.platform === cc.sys.ANDROID) {
      const cacertFile = cc.find('cacertNode').getComponent('cacert').cacertFile;
      const caPath = cacertFile.nativeUrl;
      setAdapters({
        WebSocket: (url) => new WebSocket(url, 'protobuf.1', caPath)
      });
    }
  },

  start() {
    cc.game.addPersistRootNode(cc.find("cacertNode"));

    const middleLayerData = JSON.parse(this.getMiddleLayerData());
    this.baseUrl = middleLayerData.baseUrl;
    this.middleLayerName = middleLayerData.middleLayerName;

    cc.debug.setDisplayStats(false);
    const welcomeNode = cc.find(`Canvas/welcome/${this.middleLayerName}`);
    if (welcomeNode) {
      welcomeNode.active = true;
      const canvas = cc.find('Canvas');
      canvas.getComponent(cc.Widget).updateAlignment();
      welcomeNode.scale = Math.max(
        canvas.width / welcomeNode.width,
        canvas.height / welcomeNode.height
      );
    }

    const uri = `/api/template/v1/${this.middleLayerName}`;

    this.callNetworkApiGet(this.baseUrl, uri, {}, (respData) => {
      const data = JSON.parse(respData);
      let configData = data.data.conf.web_desktop;
      if (cc.sys.os == cc.sys.OS_IOS) {
        configData = data.data.conf.ios;
      } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        configData = data.data.conf.android;
      }

      cc.assetManager.loadBundle(
        configData.bondleUrl,
        { version: configData.version },
        async (err, bundle) => {
          if (err) {
            console.log(err);
            return;
          }

          bundle.loadScene(configData.sceneName, null, null, (e, scene) => {
            if (e) {
              console.log(e);
              return;
            }
            cc.director.runScene(scene);
          });
        }
      );
    });
  },

  callNetworkApiGet(baseUrl, uri, data, callBack) {
    let queryStr = "?";
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        const value = data[key];
        queryStr += `${key}=${value}`;
      }
    }
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
        callBack(xhr.responseText);
      }
    };
    const url = `${baseUrl}${uri}${queryStr}`;
    console.log("url = " + url);
    xhr.open("GET", url, true);
    xhr.send();
  },

  getMiddleLayerData() {
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      return jsb.reflection.callStaticMethod(
        "RootViewController",
        "getMiddleLayerInfo:",
        ""
      );
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
      return jsb.reflection.callStaticMethod(
        "com/iplayabc/cocos/AppActivity",
        "getMiddleLayerInfo",
        "(Ljava/lang/String;)Ljava/lang/String;",
        ""
      );
    } else {
      return JSON.stringify({
        baseUrl: "http://staging-openapi.iteachabc.com",
        middleLayerName: "middleLayer_for_debug",
      });
    }
  },
});
