import Base64 from "crypto-js/enc-base64";
import Utf8 from "crypto-js/enc-utf8";
import AES from "crypto-js/aes";
import SHA1 from "crypto-js/sha1";

export const getBase64 = (content: string) => {
  const words = Utf8.parse(content);
  const base64Str = Base64.stringify(words);

  return base64Str;
};

export const getAES = (content: string) => {
  const KEY = "1234567890123456";
  const IV = "1234567890123456";

  const key = Utf8.parse(KEY);
  const iv = Utf8.parse(IV);
  const encrypted = AES.encrypt(content, key, { iv: iv });
  return encrypted.toString();
};

type AuthInfo = {
  method: string;
  uri: string;
  timestamp: number;
  accessKey?: string;
  token?: string;
  sessionId?: string;
};

/**
 * 获取authorisation
 * @param {Object} infos 相关信息
 * @param {String} type 类别：secret、token两种
 */
export const getAuthorization = (
  infos: AuthInfo,
  type: "secret" | "token"
): string => {
  // {type} {invoker}:base64(sha1(method&uri&timestamp&{secret}))
  if (type === "secret") {
    // accessKey | method&uri&timestamp&accessSecret
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.accessSecret}`;
    const sign = Base64.stringify(SHA1(str));
    return `Secret ${infos.accessKey}:${sign}`;
  } else if (type === "token") {
    // userId | method&uri&timestamp&token
    const str = `${infos.method.toLowerCase()}&${infos.uri}&${
      infos.timestamp
    }&${infos.token}`;
    const sign = Base64.stringify(SHA1(str));
    return `Token ${infos.sessionId}:${sign}`;
  }
};
