var y = Object.defineProperty;
var w = (p, t, e) => t in p ? y(p, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : p[t] = e;
var h = (p, t, e) => w(p, typeof t != "symbol" ? t + "" : t, e);
import { cloneDeep as x, isString as k } from "lodash";
import { parseStaticData as C } from "./sources/static.mjs";
import { parseUrlData as M } from "./sources/url.mjs";
import { parseVariableData as E } from "./sources/variable.mjs";
import { parseAPIPort as v } from "./sources/api.mjs";
import { DataSourceUtils as A } from "./utils/utils.mjs";
import { parseStorage as U } from "./sources/storage.mjs";
import { parseMqttData as B } from "./sources/mqtt.mjs";
import { parseWebSocketData as W } from "./sources/websocket.mjs";
import { MqttConnectionPoolManager as d } from "./utils/mqttConnectionPool.mjs";
import { WebSocketConnectionPoolManager as m } from "./utils/websocketConnectionPool.mjs";
import { mappingData as b } from "./utils/mappingData.mjs";
import { groupData as q } from "./utils/groupData.mjs";
import { storageData as S } from "./utils/storageData.mjs";
const c = class c {
  /**
   * 添加数据源解析器
   * @param type - 数据源类型
   * @param parser - 解析器函数
   */
  static addParser(t, e) {
    this.parsers.add({ type: t, parser: e });
  }
  /**
   * 获取数据源解析器
   * @param type - 数据源类型
   * @returns 解析器函数，如果未找到则返回undefined
   */
  static getParser(t) {
    const e = Array.from(this.parsers).find((a) => a.type === t);
    return e == null ? void 0 : e.parser;
  }
  /**
   * 解析数据源
   * @param sources 数据源
   * @param callback 回调函数
   * @param noUseMapping 是否不使用映射
   * @param isInterval 是否开启定时任务
   * @param isEditor 是否为编辑器模式
   * @returns
   */
  static parse({
    sources: t,
    callback: e = (i) => i || [],
    noUseMapping: a = !1,
    isInterval: r = !0,
    isEditor: o = !1
  }) {
    try {
      if (t.length <= 0)
        throw new Error("未找到数据源");
      t.forEach((i) => {
        this.handleDataSourceExecution(
          i,
          e,
          a,
          r,
          o
        );
      });
    } catch {
      e(null);
    }
  }
  /**
   * 处理数据源执行逻辑，根据pid确定执行顺序
   */
  static handleDataSourceExecution(t, e, a, r, o) {
    if (o) {
      this.executeDataSource(
        t,
        e,
        a,
        r,
        o
      );
      return;
    }
    const { id: i, pid: n } = t;
    if (this.initializeDataSourceState(i), this.checkAndExecuteWaitingChildren(i), n && n.toString() !== "-1") {
      const s = this.dataSourceStatePool.get(n);
      if (!s) {
        this.waitingPool.set(i, {
          item: t,
          callback: e,
          noUseMapping: a,
          isInterval: r,
          isEditor: o
        });
        return;
      }
      s.status === "completed" ? this.executeDataSource(
        t,
        e,
        a,
        r,
        o
      ) : (this.waitingPool.set(i, {
        item: t,
        callback: e,
        noUseMapping: a,
        isInterval: r,
        isEditor: o
      }), s.callbacks.push(() => {
        this.waitingPool.delete(i), this.executeDataSource(
          t,
          e,
          a,
          r,
          o
        );
      }));
    } else
      this.executeDataSource(
        t,
        e,
        a,
        r,
        o
      );
  }
  /**
   * 初始化数据源状态
   */
  static initializeDataSourceState(t) {
    this.dataSourceStatePool.has(t) || this.dataSourceStatePool.set(t, {
      id: t,
      status: "pending",
      callbacks: []
    });
  }
  /**
   * 标记数据源为执行中状态
   */
  static markDataSourceExecuting(t) {
    const e = this.dataSourceStatePool.get(t);
    e && (e.status = "executing");
  }
  /**
   * 标记数据源为已完成状态，并触发依赖它的数据源
   */
  static markDataSourceCompleted(t) {
    const e = this.dataSourceStatePool.get(t);
    if (e) {
      e.status = "completed";
      const a = [...e.callbacks];
      e.callbacks = [], a.forEach((r) => {
        try {
          r();
        } catch {
        }
      });
    }
  }
  /**
   *
   * 如果有，且当前数据源已完成，则立即执行它们。没完成加入callbacks继续等待
   */
  static checkAndExecuteWaitingChildren(t) {
    if (!this.waitingPool.size)
      return;
    const e = [];
    this.waitingPool.forEach((a, r) => {
      a.item.pid === t && e.push({ id: r, ...a });
    });
    for (const a of e) {
      const r = this.dataSourceStatePool.get(t);
      r && (r.status === "completed" ? (this.waitingPool.delete(a.id), this.executeDataSource(
        a.item,
        a.callback,
        a.noUseMapping,
        a.isInterval,
        a.isEditor
      )) : r.callbacks.push(() => {
        this.waitingPool.delete(a.id), this.executeDataSource(
          a.item,
          a.callback,
          a.noUseMapping,
          a.isInterval,
          a.isEditor
        );
      }));
    }
  }
  /**
   * 执行数据源
   */
  static executeDataSource(t, e, a, r, o) {
    this.markDataSourceExecuting(t.id), this.setupInterval(t, r, a, o, e), this.executeTask(t, a, o, (i) => {
      e(i), this.markDataSourceCompleted(t.id);
    });
  }
  /**
   * 设置定时任务
   */
  static setupInterval(t, e, a, r, o) {
    if (!e) return;
    const i = this.timerPool.get(t.id);
    if (i && (clearInterval(i), this.timerPool.delete(t.id)), t.source.isAutoUpdate) {
      const n = setInterval(() => {
        this.executeTask(t, a, r, (s) => {
          o(s);
        });
      }, t.source.autoUpdateTime * 1e3);
      this.timerPool.set(t.id, n);
    }
  }
  /**
   * 执行任务
   */
  static executeTask(t, e, a, r) {
    const o = t, { source: i } = o, n = this.getParser(i.type);
    n && n(o, e, (s) => {
      if (a) {
        r(s);
        return;
      }
      !e && o.source.mapping && o.source.mapping.length > 0 ? (S(o.source.storage, s.finalKeyData), r(s.finalKeyData)) : (S(o.source.storage, s.noMappingData), r(s.noMappingData));
    });
  }
  /**
   * 处理数据并返回最终结果
   * @param source
   * @param data
   * @param sourceId
   * @param noUseMapping
   * @returns
   */
  static processData(t, e, a, r) {
    const { filter: o, mapping: i, dynamicMapping: n, isUserdata: s } = t;
    return new Promise(function(D) {
      const P = x(e);
      c.filterData(o, e).then(
        (l) => {
          const u = {
            id: a,
            finalKeyData: { id: a, data: null },
            finalUserData: { id: a, data: null },
            filteredData: { id: a, data: l },
            rawData: { id: a, data: P },
            noMappingData: null
          };
          if (!r && i.length) {
            const f = b(
              l,
              i,
              n,
              s
            );
            u.finalKeyData.data = f.length ? q(f, i) : l, u.finalUserData.data = f.length ? f : l;
          } else
            u.finalUserData.data = l, u.noMappingData = l;
          D(u);
        }
      );
    });
  }
  /**
   * 过滤数据
   * @param filterCode
   * @param data
   * @returns
   */
  static async filterData(t, e) {
    if (!k(t))
      return e;
    try {
      let a = t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
      a = A.replaceStringVariables(a);
      const r = `
        ${a}
        if (typeof filter !== 'function') {
          throw new Error('filter function is not defined in the provided code');
        }
        return filter(data);
      `, i = new Function("data", r)(e);
      return i instanceof Promise ? await i : i;
    } catch {
      return e;
    }
  }
  /**
   * 销毁数据源
   */
  static destroy() {
    this.timerPool.forEach((t) => {
      clearInterval(t);
    }), this.timerPool.clear(), this.dataSourceStatePool.clear(), this.dataSourceStatePool = /* @__PURE__ */ new Map(), this.waitingPool.clear(), this.waitingPool = /* @__PURE__ */ new Map(), d.closeAllConnections(), m.closeAllConnections();
  }
  static clearMqttConnectionById(t) {
    d.removeConnectionByUUID(t);
  }
  static clearWebSocketConnectionById(t) {
    m.removeConnectionByUUID(t);
  }
};
/**
 * 定时器池
 */
h(c, "timerPool", /* @__PURE__ */ new Map()), /**
 * 数据源状态池 - 跟踪所有数据源的执行状态
 */
h(c, "dataSourceStatePool", /* @__PURE__ */ new Map()), /**
 * 等待执行的数据源池 - 存储因依赖关系而等待的数据源
 */
h(c, "waitingPool", /* @__PURE__ */ new Map()), /**
 * 数据源解析器
 */
h(c, "parsers", /* @__PURE__ */ new Set([
  { type: "url", parser: M },
  { type: "static", parser: C },
  { type: "variable", parser: E },
  { type: "api", parser: v },
  { type: "storage", parser: U },
  { type: "mqtt", parser: B },
  { type: "ws", parser: W }
]));
let g = c;
export {
  A as DataSourceUtils,
  g as SHJDatasourceV2
};
