// import { Constants, MESSAGETIP } from "./constants";

export const getLoaclStorageOfKey = (key: string) => {
  return JSON.parse(localStorage.getItem(key) || "{}");
};

export const isEn = () => {
  return (
    (localStorage.getItem("language") &&
      localStorage.getItem("language") === "en") ||
    [
      "www.cloudam.se",
      "47.75.109.159",
      "47.57.235.86",
      "www.cloudam.io",
    ].includes(window.location.host)
  );
};

export class ApiUtils {
  static getAuthorizationHeaders(headers: any) {
    let token_key = getLoaclStorageOfKey("token_key");
    if (!token_key) {
      if (
        window.location.pathname.indexOf("/login-page") > -1 ||
        window.location.pathname.indexOf("/pages/Internlogin-page") > -1
      ) {
        return false;
      } else {
        setTimeout(() => {
          //   localStorage.removeItem("temporary_token_key");
          //   localStorage.removeItem("token_key");
          if (
            window.location.href &&
            !window.location.href.includes("/login-page") &&
            !window.location.href.includes("/pages/Internlogin-page")
          )
            isEn()
              ? (window.location.href = "/v2/pages/Internlogin-page")
              : (window.location.href = "/v2/pages/login-page");
        }, 4000);
      }
      return false;
    }
    let token = token_key.access_token;
    headers["Authorization"] = "Bearer " + token;
    headers["Accept-Language"] =
      localStorage.getItem("language") === "en"
        ? "en-US,en;q=0.5"
        : "zh-CN,zh,q=0.5";
    return true;
  }
  // 临时token
  static getTemporaryAuthorizationHeaders(obj: any, headers: any, action: any) {
    if (!localStorage.getItem("temporary_token_key")) {
      obj.setError({
        errorCode: "x0001",
        message: "临时登陆凭证过期或失效，请重新连接云账号",
      });
      obj.emitChange(action, false);
      return false;
    }
    headers["Authorization"] =
      "Bearer " + getLoaclStorageOfKey("temporary_token_key").access_token;
    headers["Accept-Language"] =
      localStorage.getItem("language") === "en"
        ? "en-US,en;q=0.5"
        : "zh-CN,zh,q=0.5";
    return true;
  }

  static poll(fn: any, timeout: number, interval: number) {
    var endTime = Number(new Date()) + (timeout || 2000);
    interval = interval || 100;

    let hasCanceled = false;

    var checkCondition = function (resolve: any, reject: any) {
      if (hasCanceled) {
        reject({ isCanceled: true, type: "1" }); //type ===1 用户手动取消
        return;
      }
      // If the condition is met, we're done!
      var result = fn();
      if (result) {
        resolve(result);
      }
      // If the condition isn't met but the timeout hasn't elapsed, go again
      else if (Number(new Date()) < endTime) {
        setTimeout(checkCondition, interval, resolve, reject);
      }
      // Didn't match and too much time, reject!
      else {
        reject({ isCanceled: true, type: "2" });
      }
    };

    const wrappedPromise = new Promise(checkCondition);

    return {
      promise: wrappedPromise,
      cancel() {
        hasCanceled = true;
      },
    };
  }
}
