import { config } from '@grafana/runtime';
import { cloneDeep, partition, groupBy, map, every, find, head, concat } from 'lodash';

function postProcessQueryResult(annotation, results) {
  if (annotation.snapshotData) {
    annotation = cloneDeep(annotation);
    delete annotation.snapshotData;
  }
  const processed = results.map((item) => {
    var _a;
    const processedItem = { ...item };
    processedItem.source = annotation;
    processedItem.color = config.theme2.visualization.getColorByName(annotation.iconColor);
    processedItem.type = annotation.name;
    processedItem.isRegion = Boolean(processedItem.timeEnd && processedItem.time !== processedItem.timeEnd);
    switch ((_a = processedItem.newState) == null ? void 0 : _a.toLowerCase()) {
      case "pending":
        processedItem.color = "yellow";
        break;
      case "alerting":
        processedItem.color = "red";
        break;
      case "ok":
        processedItem.color = "green";
        break;
      case "normal":
        processedItem.color = "green";
        break;
      case "no_data":
        processedItem.color = "gray";
        break;
      case "nodata":
        processedItem.color = "gray";
        break;
    }
    return processedItem;
  });
  return processed;
}
function dedupAnnotations(annotations) {
  let dedup = [];
  const events = partition(annotations, "id");
  const eventsById = groupBy(events[0], "id");
  dedup = map(eventsById, (eventGroup) => {
    if (eventGroup.length > 1 && !every(eventGroup, isPanelAlert)) {
      return find(eventGroup, (event) => {
        return event.eventType !== "panel-alert";
      });
    } else {
      return head(eventGroup);
    }
  });
  dedup = concat(dedup, events[1]);
  return dedup;
}
function isPanelAlert(event) {
  return event.eventType === "panel-alert";
}
function getLikelyAnnotationEventFieldNames(annotationEvents, samples = 250) {
  const len = annotationEvents.length;
  const firstIdx = 0;
  const lastIdx = len - 1;
  const stride = Math.max(1, Math.floor((lastIdx - firstIdx + 1) / samples));
  const annotationEventNamesSet = /* @__PURE__ */ new Set();
  for (let annotationEventIndex = firstIdx; annotationEventIndex < len; annotationEventIndex += stride) {
    const annotationEvent = annotationEvents[annotationEventIndex];
    for (const key of Object.keys(annotationEvent)) {
      annotationEventNamesSet.add(key);
    }
  }
  if (len > 0) {
    for (const key of Object.keys(annotationEvents[lastIdx])) {
      annotationEventNamesSet.add(key);
    }
  }
  return Array.from(annotationEventNamesSet);
}

export { dedupAnnotations, getLikelyAnnotationEventFieldNames, postProcessQueryResult };
//# sourceMappingURL=utils.js.map
