import { LoadingState } from '@grafana/data';
import { mergeMap, of, tap, combineLatest, map } from 'rxjs';

const passthroughProcessor = (_, secondary) => of(secondary);
function combineLoadingStates(responseState) {
  var _a;
  if (responseState.some((s) => s === LoadingState.Error)) {
    return LoadingState.Error;
  }
  if (responseState.some((s) => s === LoadingState.Loading)) {
    return LoadingState.Loading;
  }
  if (responseState.some((s) => s === LoadingState.Streaming)) {
    return LoadingState.Streaming;
  }
  return (_a = responseState[0]) != null ? _a : LoadingState.Done;
}
const extraQueryProcessingOperator = (panelDataProcessors) => (data) => {
  const processedCache = /* @__PURE__ */ new WeakMap();
  return data.pipe(
    mergeMap(([primaryResponse, ...secondaryResponses]) => {
      const processedSecondaries = secondaryResponses.map((s) => {
        var _a, _b;
        const cached = processedCache.get(s);
        if (cached) {
          return of(cached);
        }
        const processedPanelData = (_b = (_a = panelDataProcessors.get(s.request.requestId)) == null ? void 0 : _a(primaryResponse, s)) != null ? _b : of(s);
        return processedPanelData.pipe(tap((out) => processedCache.set(s, out)));
      });
      return combineLatest([of(primaryResponse), ...processedSecondaries]);
    }),
    map(([processedPrimary, ...processedSecondaries]) => {
      var _a;
      const allResponses = [processedPrimary, ...processedSecondaries];
      const allResponseErrors = allResponses.flatMap((d) => {
        var _a2;
        return (_a2 = d.errors) != null ? _a2 : [];
      });
      return {
        ...processedPrimary,
        state: combineLoadingStates(allResponses.map((d) => d.state)),
        series: [...processedPrimary.series, ...processedSecondaries.flatMap((s) => s.series)],
        annotations: [
          ...(_a = processedPrimary.annotations) != null ? _a : [],
          ...processedSecondaries.flatMap((s) => {
            var _a2;
            return (_a2 = s.annotations) != null ? _a2 : [];
          })
        ],
        ...allResponseErrors.length > 0 ? { errors: allResponseErrors, error: allResponseErrors[0] } : {}
      };
    })
  );
};

export { combineLoadingStates, extraQueryProcessingOperator, passthroughProcessor };
//# sourceMappingURL=extraQueryProcessingOperator.js.map
