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() {
    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(`Настройка инициализируется, будьте терпеливы`);

    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/v2/${this.middleLayerName}`;
    // 正在检查更新
    this.setMiddleLayerProgress(`Проверяется обновление`);
    this.callNetworkApiGet(this.baseUrl, uri, {}, (respData) => {
      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) => {
        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) => {
            if (err) {
              console.log(err);
              return;
            }
            bundle.loadScene(sceneName, null, (finish, total, item) => {
              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秒有没有响应 - 重新请求 
        // 请求失败，重试第${i+1}次
				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;
    }
  },
});
