import { getTemplateSrv, getDataSourceSrv } from '@grafana/runtime';
import { AdHocFiltersVariable, isGroupByFilter } from './AdHocFiltersVariable.js';
import { interpolate } from '../../core/sceneGraph/sceneGraph.js';

let originalGetAdhocFilters = void 0;
const allActiveFilterSets = /* @__PURE__ */ new Set();
function patchGetAdhocFilters(filterVar) {
  filterVar.addActivationHandler(() => {
    allActiveFilterSets.add(filterVar);
    return () => allActiveFilterSets.delete(filterVar);
  });
  if (originalGetAdhocFilters) {
    return;
  }
  const templateSrv = getTemplateSrv();
  if (!(templateSrv == null ? void 0 : templateSrv.getAdhocFilters)) {
    console.log("Failed to patch getAdhocFilters");
    return;
  }
  originalGetAdhocFilters = templateSrv.getAdhocFilters;
  templateSrv.getAdhocFilters = function getAdhocFiltersScenePatch(dsName) {
    var _a;
    if (allActiveFilterSets.size === 0) {
      return originalGetAdhocFilters.call(templateSrv, dsName);
    }
    const ds = getDataSourceSrv().getInstanceSettings(dsName);
    if (!ds) {
      return [];
    }
    for (const filter of allActiveFilterSets.values()) {
      if (((_a = filter.state.datasource) == null ? void 0 : _a.uid) === ds.uid) {
        return filter.state.filters.filter((f) => !isGroupByFilter(f));
      }
    }
    return [];
  }.bind(templateSrv);
}
function findAllAdHocFiltersInHierarchy(dsUid, sceneObject) {
  var _a, _b, _c;
  const found = [];
  let current = sceneObject;
  while (current) {
    const variables = (_b = (_a = current.state.$variables) == null ? void 0 : _a.state.variables) != null ? _b : [];
    for (const variable of variables) {
      if (variable instanceof AdHocFiltersVariable && interpolate(variable, (_c = variable.state.datasource) == null ? void 0 : _c.uid) === dsUid) {
        found.push(variable);
      }
    }
    current = current.parent;
  }
  return found.reverse();
}
function findGlobalAdHocFilterVariableByUid(dsUid) {
  var _a;
  for (const filter of allActiveFilterSets.values()) {
    if (interpolate(filter, (_a = filter.state.datasource) == null ? void 0 : _a.uid) === dsUid) {
      return filter;
    }
  }
  return void 0;
}

export { allActiveFilterSets, findAllAdHocFiltersInHierarchy, findGlobalAdHocFilterVariableByUid, patchGetAdhocFilters };
//# sourceMappingURL=patchGetAdhocFilters.js.map
