var x = Object.defineProperty;
var k = (l, t, e) => t in l ? x(l, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[t] = e;
var h = (l, t, e) => k(l, typeof t != "symbol" ? t + "" : t, e);
import { cloneDeep as C, isString as M } from "lodash";
import { parseStaticData as v } from "./sources/static.mjs";
import { parseUrlData as A } from "./sources/url.mjs";
import { parseVariableData as E } from "./sources/variable.mjs";
import { parseAPIPort as U } from "./sources/api.mjs";
import { DataSourceUtils as B } from "./utils/utils.mjs";
import { parseStorage as T } from "./sources/storage.mjs";
import { parseMqttData as W } from "./sources/mqtt.mjs";
import { parseWebSocketData as q } from "./sources/websocket.mjs";
import { MqttConnectionPoolManager as S } from "./utils/mqttConnectionPool.mjs";
import { WebSocketConnectionPoolManager as D } from "./utils/websocketConnectionPool.mjs";
import { mappingData as K } from "./utils/mappingData.mjs";
import { groupData as b } from "./utils/groupData.mjs";
import { storageData as g } 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) {
    if (o) {
      this.executeTask(t, a, o, (i) => {
        e(i);
      });
      return;
    }
    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.markDataSourceExecuting(t.id), this.executeTask(t, a, r, (s) => {
          o(s), this.markDataSourceCompleted(t.id);
        });
      }, 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 ? (g(o.source.storage, s.noMappingData), r(s.noMappingData)) : (g(o.source.storage, s.finalKeyData), r(s.finalKeyData));
    });
  }
  /**
   * 处理数据并返回最终结果
   * @param source
   * @param data
   * @param sourceId
   * @param noUseMapping
   * @returns
   */
  static processData(t, e, a, r) {
    const { filter: o, mapping: i, dynamicMapping: n, isUserdata: s } = C(t);
    return new Promise(function(y) {
      const w = e;
      c.filterData(o, e).then(
        (p) => {
          var d;
          const u = {
            id: a,
            finalKeyData: { id: a, data: null },
            finalUserData: { id: a, data: null },
            filteredData: { id: a, data: p },
            rawData: { id: a, data: w },
            noMappingData: null
          };
          if (r)
            u.finalUserData.data = u.noMappingData = p;
          else {
            const f = K(
              p,
              i,
              n,
              s
            ), m = !!((d = f.mappedData) != null && d.length);
            u.finalKeyData.data = m ? b(f.mappedData, f.finalMapping) : p, u.finalUserData.data = m ? f.mappedData : p;
          }
          y(u);
        }
      );
    });
  }
  /**
   * 过滤数据
   * @param filterCode
   * @param data
   * @returns
   */
  static async filterData(t, e) {
    if (!M(t))
      return e;
    try {
      let a = t.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "");
      a = B.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(), S.closeAllConnections(), D.closeAllConnections();
  }
  static clearMqttConnectionById(t) {
    S.removeConnectionByUUID(t);
  }
  static clearWebSocketConnectionById(t) {
    D.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: A },
  { type: "static", parser: v },
  { type: "variable", parser: E },
  { type: "api", parser: U },
  { type: "storage", parser: T },
  { type: "mqtt", parser: W },
  { type: "ws", parser: q }
]));
let P = c;
export {
  B as DataSourceUtils,
  P as SHJDatasourceV2
};
