export function getGlobal(): any {
  // @ts-ignore
  if (typeof window !== "undefined") return window;
  // @ts-ignore
  if (typeof global !== "undefined") return global;
  return {};
}

// 这里发出的消息接收时会自动转，确保保持原样
export function toString(v: any, def?: string) {
  try {
    if (typeof v === "string") return v;
    return JSON.stringify(v);
  } catch (err) {
    return def || "";
  }
}

export function toParse(v: any, def?: {}) {
  if (v === undefined || v === "") return def;
  if (typeof v === "object") return v;
  try {
    return JSON.parse(v);
  } catch (err) {
    return def;
  }
}

/**
 * 渲染err对象
 * @param err
 * @param def
 * @returns
 */
export function readErrObj(v: any, def?: any) {
  // err对象要读property的属性
  try {
    const keys = Object.getOwnPropertyNames(v);
    const nkeys = keys.filter((key) => key !== "stack");
    return JSON.parse(JSON.stringify(v, nkeys));
  } catch (err) {
    return def || {};
  }
}

/**
 * SDK.xx.xx 通过path提取
 * @param SDK
 * @param paths
 * @returns
 */
export function getStack(SDK: any, paths: string) {
  const pathArray = paths.split(".");
  let stack = SDK;
  let i = 0;
  let pathName;

  if (!stack) return;

  while (i < pathArray.length) {
    pathName = pathArray[i];
    stack = stack[pathName];
    if (!stack) return;
    i++;
  }

  return stack;
}

/**
 * 生成6位唯一key
 * @returns
 */
export function genUnikey(len: number = 6) {
  return Math.random().toString(36).substr(-len);
}
