import { _decorator, Component, Node } from "cc";
import PogHttp, { PogLoginResp } from "./net/PogHttp";
import { WalletManager } from "./web3/WalletManager";
import { director } from "cc";
import BaseUI from "./base/BaseUI";
import { WS } from "./net/WS";
import { ProgressBar } from "cc";
import LoginM from "./mgr/LoginM";
import AB from "./base/AB";
import ConfigM from "./api/ConfigM";
import WsM from "./api/WsM";
import UserM from "./api/UserM";
import Utils from "./utils/Utils";
import { LanguageManager } from "./utils/LanguageManager";
const { ccclass, property } = _decorator;

@ccclass("Loading")
export class Loading extends BaseUI {
  showLoginByWalletButton() {
    this.FindNode("btn_login").active = true;
  }
  private static _ins: Loading;
  public static get ins(): Loading {
    return Loading._ins;
  }

  Q_Click_Login() {
    // this.FindNode("btn_login").active = false;
    window.location.reload();
    // WalletManager.ins.open();
  }

  private LoadingEnable: boolean = true;

  public async U(text: string, progress: number) {
    const progressBar = Loading.ins.progressBar;

    await Loading.ins.setText("lbl_progress_info", text);
    let fromProgress = progressBar.progress;
    let toProgress = progress;

    if (fromProgress >= toProgress) {
      return;
    }

    let duration = Math.random() * 0.5 + 0.01;
    let elapsed = 0;
    let deltaTime = 0.01;
    while (elapsed < duration && this.LoadingEnable) {
      elapsed += deltaTime;
      let t = elapsed / duration;
      let progress = fromProgress + (toProgress - fromProgress) * t;
      if (!progressBar) {
        console.warn("progressBar is null", text, progress);
        return;
      }
      progressBar.progress = progress;
      let pp = progress * 100;
      if (pp > 100) {
        pp = 100;
      }
      pp = Math.floor(pp);
      await Loading.ins.setText("lbl_progress_value", pp + "%");
      await new Promise((resolve) => setTimeout(resolve, 10));
    }
  }
  private progressBar: ProgressBar;
  protected async onLoad(): Promise<void> {
    let self = this;
    self.progressBar = self.FindAs("ProgressBar", ProgressBar);
    self.progressBar.progress = 0;

    self.FindNode("btn_login").active = false;
    self.FindNode("btn_retry").active = false;
    this.setText("lbl_version_info", ConfigM.ins.getVersionText());

    LanguageManager.switchLanguage("en");
    await this.login();
  }

  public async loginFailed() {
    let self = this;

    WalletManager.ins.disconnect();
    await this.U("Login failed...", 1);
    if (PogHttp.ins.lastError) {
      await this.U(PogHttp.ins.lastError, 1);
    }
    self.FindNode("btn_retry").active = true;
  }

  protected onDestroy(): void {
    this.LoadingEnable = false;
    Loading._ins = null;
  }
  async login() {

   

    Loading._ins = this;
    // new window["VConsole"]();

    let self = this;

    let result = await LoginM.ins.login();
    console.warn("result", result);

    if (result) {
      await this.onLoginSuccess(result);
    } else {
     
      await this.loginFailed();
    }
  }

  async onLoginSuccess(res: PogLoginResp) {
    let self = this;
    if (!res) {
      await this.loginFailed();
      self.FindNode("btn_retry").active = true;
      return;
    }

    await self.U("Logging Success...", 0.7);
    await new Promise((resolve) => setTimeout(resolve, 10));

    let config = await ConfigM.ins.loadConfig();

    if (!config) {
      self.U("Loading config failed...", 1);
      await this.loginFailed();
      return;
    }

    self.U("Loading config success...", 0.7);
    await new Promise((resolve) => setTimeout(resolve, 30));

    self.U("Loading Assets ...", 0.8);
    let ab = await AB.ins.loadInLoading();
    await new Promise((resolve) => setTimeout(resolve, 10));
    self.U("Loading Assets success...", 0.8);

    let connectResult = await WS.ins.connect(res.wsUrl, res.token);
    if (!connectResult) {
      this.U("Connect websocket failed...", 1);
      await this.loginFailed();
      return;
    }

    await new Promise((resolve) => setTimeout(resolve, 300));

    await self.U("Get user info...", 0.8);
    let userInfo = await UserM.ins.userInfo();
    if (!userInfo&&Utils.getQueryString("skip")!="123") {
      this.U("Get user info failed...", 1);
      await this.loginFailed();
      return;
    }
    await self.U("Entering hall...", 1);
    await new Promise((resolve) => setTimeout(resolve, 30));

    director.loadScene("hall");
  }

  showLoading(arg0: boolean) {}
}
