// @ts-ignore
import { initWeb3, web3Sign, web3 } from "./web3";
import { getSignRawData } from "../user";
// @ts-ignore
import { killSession, walletConnect, walletConnectSign } from "./walletConnect";
import "./tronweb";

export const LoginType = {
  Web3: "web3",
  QrCode: "qrcode"
};
const state = {
  type: ""
};

export function getState() {
  return state;
}

export async function loginWithWeb3() {
  await initWeb3();
  state.type = LoginType.Web3;
  localStorage.setItem("loginType", LoginType.Web3);
}

export async function loginWithQrCode(kill = false, autoCreate = false) {
  await walletConnect(kill, autoCreate);
  state.type = LoginType.QrCode;
  localStorage.setItem("loginType", LoginType.QrCode);
}

export function walletLogout() {
  killSession();
  state.type = "";
}

export async function walletSign() {
  const { data }: any = await getSignRawData();
  // const data = '1234';
  var sign;
  var rawData;
  switch (state.type) {
    case LoginType.Web3:
      rawData = web3.utils.fromUtf8(data);
      sign = await web3Sign(rawData);
      break;
    case LoginType.QrCode:
      // rawData = web3.utils.keccak256(data);
      rawData = web3.utils.fromUtf8(data);
      sign = await walletConnectSign(rawData);
      break;
  }
  console.log("rawData:", rawData);
  return {
    raw: data,
    sign
  };
}

// 在登录过的情况下自动保持连接
if (localStorage.getItem("loginType") === LoginType.QrCode) {
  loginWithQrCode(false, false);
} else if (localStorage.getItem("loginType") === LoginType.Web3) {
  loginWithWeb3();
}
