import { arrayToDataFrame, DataTopic } from '@grafana/data';
import { LoadingState } from '@grafana/schema';
import React from 'react';
import { map } from 'rxjs';
import { emptyPanelData } from '../../../core/SceneDataNode.js';
import { sceneGraph } from '../../../core/sceneGraph/index.js';
import { getDataSource } from '../../../utils/getDataSource.js';
import { getMessageFromError } from '../../../utils/getMessageFromError.js';
import { writeSceneLog } from '../../../utils/writeSceneLog.js';
import { registerQueryWithController } from '../../registerQueryWithController.js';
import { SceneDataLayerBase } from '../SceneDataLayerBase.js';
import { executeAnnotationQuery } from './standardAnnotationQuery.js';
import { postProcessQueryResult, dedupAnnotations, getLikelyAnnotationEventFieldNames } from './utils.js';
import { wrapInSafeSerializableSceneObject } from '../../../utils/wrapInSafeSerializableSceneObject.js';
import { RefreshEvent } from '@grafana/runtime';
import { DrilldownDependenciesManager } from '../../../variables/DrilldownDependenciesManager.js';
import { InlineSwitch } from '@grafana/ui';
import { css } from '@emotion/css';

class AnnotationsDataLayer extends SceneDataLayerBase {
  constructor(initialState) {
    super(
      {
        isEnabled: true,
        ...initialState
      },
      ["query"]
    );
    this._scopedVars = {
      __sceneObject: wrapInSafeSerializableSceneObject(this)
    };
    this._drilldownDependenciesManager = new DrilldownDependenciesManager(this._variableDependency);
  }
  onEnable() {
    this.publishEvent(new RefreshEvent(), true);
    const timeRange = sceneGraph.getTimeRange(this);
    this.setState({
      query: {
        ...this.state.query,
        enable: true
      }
    });
    this._timeRangeSub = timeRange.subscribeToState(() => {
      setTimeout(() => this.runWithTimeRange(timeRange), 0);
    });
  }
  onDisable() {
    var _a;
    this.publishEvent(new RefreshEvent(), true);
    this.setState({
      query: {
        ...this.state.query,
        enable: false
      }
    });
    (_a = this._timeRangeSub) == null ? void 0 : _a.unsubscribe();
  }
  runLayer() {
    writeSceneLog("AnnotationsDataLayer", "run layer");
    const timeRange = sceneGraph.getTimeRange(this);
    this.runWithTimeRange(timeRange);
  }
  async runWithTimeRange(timeRange) {
    var _a;
    const { query } = this.state;
    if (!query.enable) {
      return;
    }
    this._drilldownDependenciesManager.findAndSubscribeToDrilldowns((_a = query.datasource) == null ? void 0 : _a.uid, this);
    if (this.querySub) {
      this.querySub.unsubscribe();
    }
    if (this._variableDependency.hasDependencyInLoadingState()) {
      writeSceneLog("AnnotationsDataLayer", "Variable dependency is in loading state, skipping query execution");
      return;
    }
    try {
      const ds = await this.resolveDataSource(query);
      let stream = executeAnnotationQuery(
        ds,
        timeRange,
        query,
        this,
        this._drilldownDependenciesManager.getFilters(),
        this._drilldownDependenciesManager.getGroupByKeys()
      ).pipe(
        registerQueryWithController({
          type: "AnnotationsDataLayer/annotationsLoading",
          origin: this,
          cancel: () => this.cancelQuery()
        }),
        map((events) => {
          const stateUpdate = this.processEvents(query, events);
          return stateUpdate;
        })
      );
      this.querySub = stream.subscribe((stateUpdate) => {
        this.publishResults(stateUpdate);
      });
    } catch (e) {
      this.publishResults({
        ...emptyPanelData,
        state: LoadingState.Error,
        errors: [
          {
            message: getMessageFromError(e)
          }
        ]
      });
      console.error("AnnotationsDataLayer error", e);
    }
  }
  async resolveDataSource(query) {
    return await getDataSource(query.datasource || void 0, this._scopedVars);
  }
  processEvents(query, events) {
    let processedEvents = postProcessQueryResult(query, events.events || []);
    processedEvents = dedupAnnotations(processedEvents);
    const stateUpdate = { ...emptyPanelData, state: events.state };
    const names = getLikelyAnnotationEventFieldNames(processedEvents);
    const df = arrayToDataFrame(processedEvents, names);
    df.meta = {
      ...df.meta,
      dataTopic: DataTopic.Annotations
    };
    stateUpdate.series = [df];
    return stateUpdate;
  }
}
AnnotationsDataLayer.Component = AnnotationsDataLayerRenderer;
function AnnotationsDataLayerRenderer({ model }) {
  const { isEnabled, isHidden } = model.useState();
  const elementId = `data-layer-${model.state.key}`;
  if (isHidden) {
    return null;
  }
  return /* @__PURE__ */ React.createElement(
    InlineSwitch,
    {
      className: switchStyle,
      id: elementId,
      value: isEnabled,
      onChange: () => model.setState({ isEnabled: !isEnabled })
    }
  );
}
const switchStyle = css({
  borderBottomLeftRadius: 0,
  borderTopLeftRadius: 0
});

export { AnnotationsDataLayer };
//# sourceMappingURL=AnnotationsDataLayer.js.map
