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)
      });
    }
  },

  reviewFlag: false,
  async start() {
    console.log(' in debug shell start 1');
    cc.game.addPersistRootNode(cc.find("cacertNode"));

    const middleLayerData = JSON.parse(this.getMiddleLayerData());
    this.baseUrl = middleLayerData.baseUrl;
    this.middleLayerName = middleLayerData.middleLayerName;
    if (this.baseUrl.indexOf(`staging-`) > 0) {
      this.DOMAIN = "http://staging-teach.cdn.ireadabc.com/";
    } else {
      this.DOMAIN = "http://teach.cdn.ireadabc.com/";
    }

    const reviewFlag = await this.getIOSReviewFlag();
    this.reviewFlag = reviewFlag == 1 ? true : false;

    this.setMiddleLayerProgress(`正在初始化配置，请耐心等待`);

    console.log(' in debug shell start 2');

    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
      );

    console.log(' in debug shell start 3');

    }

    console.log(' in debug shell start 4');


    const uri = `/api/template/v2/${this.middleLayerName}`;
    this.setMiddleLayerProgress(`正在检查更新`);
    this.callNetworkApiGet(this.baseUrl, uri, {}, (respData) => {

    console.log(' in debug shell start 5');

      const data = JSON.parse(respData).data;
      let sceneName, version, bondleUrl = "";

      this.setMiddleLayerProgress(`正在检查配置文件`);
      const templateBaseUrl = `${this.DOMAIN}h5template/${data.name}/v${data.last_version}`;
      this.callNetworkApiGet(templateBaseUrl, '/config.json', {}, (conf) => {

    console.log(' in debug shell start 6');

        conf = JSON.parse(conf);
        sceneName = conf.android.sceneName;
        version = "";
        bondleUrl = `${templateBaseUrl}/web_desktop`;
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
					sceneName = conf.ios.sceneName;
					version = conf.ios.version;
					bondleUrl = `${templateBaseUrl}/ios/${conf.ios.sceneName}`;
				} 
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
					sceneName = conf.android.sceneName;
					version = conf.android.version;
					bondleUrl = `${templateBaseUrl}/android/${conf.ios.sceneName}`;
				}

        this.setMiddleLayerProgress(`正在加载最新的配置文件`);
        cc.assetManager.loadBundle( bondleUrl, { version: version }, async (err, bundle) => {

    console.log(' in debug shell start 7');

            if (err) {
              console.log(err);
              return;
            }
            bundle.loadScene(sceneName, null, (finish, total, item) => {

    console.log(' in debug shell start 8');

              const p = Math.floor(finish / total * 100);
              this.setMiddleLayerProgress(`正在下载资源 ${p}%`);
            }, (e, scene) => {
              if (e) {
                console.log(e);
                return;
              }
              this.setMiddleLayerProgress(`资源下载完成，正在更新`);
              cc.director.runScene(scene);
            });
          }
        );

      }); 
    });
  },
  
  getIOSReviewFlag() {
    return new Promise((resolve, reject) => {
      this.callNetworkApiGet(this.baseUrl, '/test/appstore/reviewing', {}, (respData) => {
        resolve(respData);
      })
    })
  },

  async callNetworkApiGet(baseUrl, uri, data, callBack) {
    let queryStr = '?';
		const params = [];
		for (const key in data) {
			if (Object.hasOwnProperty.call(data, key)) {
				params.push(`${key}=${data[key]}`);
			}
		}
		queryStr += params.join("&");
    const url = `${baseUrl}${uri}${queryStr}`;

    // 如果请求失败 最多尝试5次重连
		for(let i=0; i<5; i++) {
			const result = await this.newXMLHttpRequest(url)
			if(result != null) {
				// 正常响应
				callBack(result)
				break
			} else {
				// 5秒有没有响应 - 重新请求
				this.setMiddleLayerProgress(`请求失败，重试第${i+1}次`)
			}
		}
  },

  newXMLHttpRequest(url) {
		return new Promise((resovle, reject) => {
			const xhr = new XMLHttpRequest();

			// 设置定时器 5秒终止连接
			let timeoutId = setTimeout(() => {
				xhr.abort();
				resovle(null)
			}, 5000);

			xhr.onreadystatechange = () => {
				if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
					// 如果有定时器, 清除定时器
					if(timeoutId) {
						clearTimeout(timeoutId);
						timeoutId = null;
					}
										
					resovle(xhr.responseText);
				}
			};
			
			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_JJ",
      });
    }
  },

  setMiddleLayerProgress(str = "") {
    if(this.reviewFlag) {
      return
    }
    if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
      return jsb.reflection.callStaticMethod(
        "RootViewController",
        "middleLayerProgress:",
        str
      );
    } else if (cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID) {
      return jsb.reflection.callStaticMethod(
        "com/iplayabc/cocos/AppActivity",
        "middleLayerProgress",
        "(Ljava/lang/String;)Ljava/lang/String;",
        str
      );
    } else {
      console.log(`加载进度：${str}`);
      return null;
    }
  },
});
