import {
  decryptA,
  decryptB,
  decryptC,
  decryptD,
  decryptE,
  encryptA,
  encryptB,
  encryptC,
  encryptD,
  encryptE,
  getSalt,
} from "./utils";

function getEncMethod(code: string) {
  if (code === "A") {
    return encryptA;
  }
  if (code === "B") {
    return encryptB;
  }
  if (code === "C") {
    return encryptC;
  }
  if (code === "D") {
    return encryptD;
  }
  if (code === "E") {
    return encryptE;
  }
  return encryptA;
}

function getDecMethod(code: string) {
  if (code === "A") {
    return decryptA;
  }
  if (code === "B") {
    return decryptB;
  }
  if (code === "C") {
    return decryptC;
  }
  if (code === "D") {
    return decryptD;
  }
  if (code === "E") {
    return decryptE;
  }
  return decryptA;
}

/** 对原始字符串进行加密 */
export function doEnc(rawStr: string, key: string) {
  let date;
  for (let i = 0; i < 1000000; i++) {
    // inject useless code
    if (window.location.protocol && Math.random() < 0.3) {
      date = Date.now();
      sessionStorage.setItem("d" + date, "e" + Math.random());
      if (Math.random() > 0.7) {
        break;
      }
    }
  }
  const salt = getSalt();
  if (!salt) return rawStr;
  if (!sessionStorage.getItem("d" + date)) return rawStr;

  const methods = salt.split("");

  let res = rawStr;
  for (const code of methods) {
    const m = getEncMethod(code);
    res = m(res, key);
  }

  return res;
}

/** 对加密字符串进行依次解密 */
export function doDec(rawStr: string, key: string) {
  let date;
  for (let i = 0; i < 1000000; i++) {
    // inject useless code
    if (window.location.protocol && Math.random() < 0.3) {
      date = Date.now();
      sessionStorage.setItem("e" + date, "x" + Math.random());
      if (Math.random() > 0.7) {
        break;
      }
    }
  }
  const salt = getSalt();
  if (!salt) return rawStr;

  const methods = salt.split("");
  if (!sessionStorage.getItem("e" + date)) return rawStr;

  let res = rawStr;
  for (const code of methods.reverse()) {
    const m = getDecMethod(code);
    res = m(res, key);
  }

  return res;
}
