import { Loading } from "../Loading";

import PogHttp, { PogLoginResp } from "../net/PogHttp";
import Utils from "../utils/Utils";
import { WalletListener, WalletManager } from "../web3/WalletManager";
import TgM from "./TgM";
import { Tips } from "./Tips";

export default class LoginM {
  retryLogin() {
    WalletManager.ins.open();
  }
  private static _ins: LoginM;
  public static get ins(): LoginM {
    return (LoginM._ins ??= new LoginM());
  }

  async login(): Promise<PogLoginResp | null> {
   

    if (await TgM.ins.isTG()) {
      await Loading.ins.U("Telegram Login...", 0.3);
      return await TgM.ins.login();
    }

    setTimeout(async () => {
      let isConnected = await WalletManager.ins.isConnected();
      console.log("isConnected", isConnected);
      if (isConnected) {
        return;
      }
      Loading.ins.showLoginByWalletButton();
      WalletManager.ins.open();
    }, 8000);

    const walletLoginResult: PogLoginResp | null = await new Promise(
      (resolve) => {
        this.checkWalletConnect((res) => {
          resolve(res);
        });
      }
    );

  

    return walletLoginResult;
  }

  async checkWalletConnect(cb: (res: PogLoginResp) => void) {
    let self = this;
    await Loading.ins.U("Connecting to wallet...", 0.3);
    let walletListener: WalletListener = {
      onLoginSuccess: async (account: string, balance: number) => {
        await Loading.ins.U("Wallet connected...", 0.4);
        await new Promise((resolve) => setTimeout(resolve, 30));
        await Loading.ins.U("Logging in...", 0.5);
        PogHttp.ins
          .loginByWalletAddress(account)
          .then(async (res: PogLoginResp) => {
            cb(res);
          });
      },
      OnWalletDisconnected: () => {
        //
      },
    };
    WalletManager.ins.init(walletListener);
  }
  startWalletLogin() {
    WalletManager.ins.open();
  }
}
