var f = Object.defineProperty;
var d = (l, e, a) => e in l ? f(l, e, { enumerable: !0, configurable: !0, writable: !0, value: a }) : l[e] = a;
var c = (l, e, a) => d(l, typeof e != "symbol" ? e + "" : e, a);
import { cloneDeep as h } from "lodash";
import { SHJDatasourceV2 as b } from "../index.mjs";
import "../../event/actions/fullScreenAction.mjs";
import { EventUtils as m } from "../../event/utils/utils.mjs";
const r = class r {
  static replaceURLVariables(e) {
    try {
      const a = e.match(/\${(.*?)}/g);
      if (a)
        for (let t = 0; t < a.length; t++) {
          const i = a[t].substring(2, a[t].length - 1), s = r.extractVariableName(i), n = this.getVariables().find(
            (u) => u.name === s
          );
          if (!n)
            continue;
          const o = r.getNestedValue(
            n._value,
            i.substring(s.length)
          );
          e = e.replaceAll(a[t], o);
        }
      return e;
    } catch {
      return e;
    }
  }
  static replaceObjectVariables(e) {
    const a = this.replaceStringVariables(JSON.stringify(e));
    return JSON.parse(a);
  }
  static replaceStringVariables(e) {
    try {
      const a = e.match(/\$g{(.*?)}/g);
      if (a)
        for (let t = 0; t < a.length; t++) {
          const i = a[t].substring(3, a[t].length - 1), s = this.extractVariableName(i), n = this.getVariables().find(
            (u) => u.name === s
          );
          if (!n)
            continue;
          const o = this.getNestedValue(
            n._value,
            i.substring(s.length)
          );
          e = e.replaceAll(a[t], o);
        }
      return e;
    } catch {
      return e;
    }
  }
  static getURLVariableNames(e) {
    const a = [], t = e.match(/\${(.*?)}/g);
    if (t)
      for (let i = 0; i < t.length; i++) {
        const s = t[i].substring(2, t[i].length - 1), n = r.extractVariableName(s);
        a.push(n);
      }
    return a;
  }
  static getObjectVariableNames(e) {
    return this.getStringVariableNames(JSON.stringify(e));
  }
  static getStringVariableNames(e) {
    const a = [], t = e.match(/\$g{(.*?)}/g);
    if (t)
      for (let i = 0; i < t.length; i++) {
        const s = t[i].substring(3, t[i].length - 1), n = this.extractVariableName(s);
        a.push(n);
      }
    return a;
  }
  /**
   * 获取环境变量
   * @returns 环境变量
   */
  static getEnvironments() {
    return window._apiEnvironment;
  }
  /**
   * 设置环境变量
   * @param environments 环境变量
   */
  static setEnvironments(e) {
    const a = e.find((t) => t.selected);
    a && (window._apiEnvironment = {
      envName: a.envName,
      envBaseUrl: a.envBaseUrl
    });
  }
  /**
   * 获取变量数据
   * @returns 变量数据
   */
  static getVariables() {
    return window._variables || [];
  }
  /**
   * 设置变量数据
   * @param variable 变量数据
   */
  static setVariables(e) {
    window._variables = h(e), window._variables.forEach((a) => {
      a._callbacks ?? (a._callbacks = /* @__PURE__ */ new Map());
    });
  }
  /**
   *
   * @param id
   * @returns
   */
  static getVariableById(e) {
    return window._variables.find((a) => a.id === e);
  }
  /**
   *
   * @param name
   * @returns
   */
  static getVariableByName(e) {
    return window._variables.find((a) => a.name === e);
  }
  /**
   *
   * @param name
   * @returns
   */
  static getVariableValueByName(e) {
    const a = window._variables.find((t) => t.name === e);
    return a ? a._value : null;
  }
  /**
   *
   * @param name
   * @returns
   */
  static getVariableInitialStateByName(e) {
    const a = window._variables.find((t) => t.name === e);
    return a ? a._initialState : null;
  }
  /**
   * 设置变量数据
   * @param id 变量 ID
   * @param variable 变量数据
   */
  static setVariableById(e, a, t = !0) {
    const i = this.getVariableById(e.id);
    i && (i._value = a, i._initialState ?? (i._initialState = !0), i._callbacks ?? (i._callbacks = /* @__PURE__ */ new Map()), i._callbacks.forEach(
      (s) => s(e._value)
    ), t && m.updateWidgetVariableData(i));
  }
  /**
   * 检查 WebSocket 是否已存在且有效
   * @param wsInstances WebSocket 实例
   * @param tId WebSocket 实例的 ID
   * @param sourceId WebSocket 实例的源 ID
   * @returns 是否有效
   */
  static hasValidWebSocket(e, a, t) {
    const i = e.get(a);
    if (!i) return !1;
    for (const s of i)
      if (s.getId() === t && s.isConnected())
        return !0;
    return !1;
  }
  /**
   * 只在必要时清理 WebSocket 连接
   * @param wsInstances WebSocket 实例
   * @param sourceIds 源 ID
   * @param tId WebSocket 实例的 ID
   */
  static cleanupPreviousWebSockets(e, a, t) {
    const i = e.get(t);
    i && (i.forEach((s) => {
      a.includes(s.getId()) || (s.disconnect(), i.delete(s));
    }), i.size === 0 && e.delete(t));
  }
  /**
   * 使用 Function 构造函数获取对象中的嵌套值（更简洁但安全性较低）
   * @param obj 源对象
   * @param path 路径字符串，例如 ".a[0].value"
   * @returns 获取到的值，如果路径不存在则返回 undefined
   */
  static getNestedValue(e, a) {
    try {
      return a ? new Function("obj", `return obj${a}`)(e) : e;
    } catch {
      return;
    }
  }
  /**
   * 从路径字符串中提取变量名
   * @param path 路径字符串，例如 "测试.test" 或 "333[0].aa"
   * @returns 提取出的变量名
   */
  static extractVariableName(e) {
    const a = e.match(
      /^([\u4e00-\u9fa5a-zA-Z0-9_][\u4e00-\u9fa5a-zA-Z0-9_]*)/
    );
    return a ? a[1] : "";
  }
  /**
   * 初始化所有变量
   * @param variableData
   * @returns
   */
  static executeAllVariable(e) {
    e.forEach((a) => {
      a.sources.isVariable = !0;
    }), r.setVariables(e), e.forEach((a) => {
      b.parse({
        sources: [a.sources],
        noUseMapping: !0,
        callback: (t) => {
          r.setVariableById(a, t, !1);
        }
      });
    });
  }
  /**
   * 返回空数据
   * @param id 数据源 ID
   * @returns 空数据
   */
  static noneData(e) {
    return {
      id: e,
      finalKeyData: { id: e, data: null },
      finalUserData: { id: e, data: null },
      filteredData: null,
      rawData: null,
      noMappingData: null
    };
  }
};
/**
 * 新增变量
 * @param data
 */
c(r, "addVariable", (e) => {
  b.parse({
    sources: [e.sources],
    noUseMapping: !0,
    callback: (a) => {
      r.getVariables().push(e), r.setVariableById(e, a, !1);
    }
  });
}), /**
 * 更新变量
 * @param data
 */
c(r, "updateVariable", (e) => {
  b.parse({
    sources: [e.sources],
    noUseMapping: !0,
    callback: (a) => {
      r.setVariableById(e, a, !1);
    }
  });
}), /**
 * 更新变量
 * @param data
 */
c(r, "deleteVariableById", (e) => {
  const a = window._variables.findIndex((t) => t.id === e);
  a > -1 && window._variables.splice(a, 1);
});
let g = r;
export {
  g as DataSourceUtils
};
