import { ACTION, ACTION_SUBJECT, EVENT_TYPE } from '../analytics';
import { stopMeasure } from '../performance-measures';

// This was existing logic when converting from ReactNodeView
// our current sampling for this event is not bound by node.type
let nodeViewRenderedEventsCounter = 0;
const DEFAULT_SAMPLING_RATE = 100;
const DEFAULT_SLOW_THRESHOLD = 7;
export function getPerformanceOptions(view) {
  var _nodeViewTracking$sam, _nodeViewTracking$slo;
  // Please, do not copy or use this kind of code below
  // @ts-ignore
  const fakePluginKey = {
    key: 'analyticsPlugin$',
    getState: state => {
      // Ignored via go/ees005
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      return state['analyticsPlugin$'];
    }
  };
  const pluginState = fakePluginKey.getState(view.state);
  const nodeViewTracking = pluginState && pluginState.performanceTracking ? pluginState.performanceTracking.nodeViewTracking || {} : {};
  const samplingRate = (_nodeViewTracking$sam = nodeViewTracking.samplingRate) !== null && _nodeViewTracking$sam !== void 0 ? _nodeViewTracking$sam : DEFAULT_SAMPLING_RATE;
  const slowThreshold = (_nodeViewTracking$slo = nodeViewTracking.slowThreshold) !== null && _nodeViewTracking$slo !== void 0 ? _nodeViewTracking$slo : DEFAULT_SLOW_THRESHOLD;
  return {
    trackingEnabled: !!nodeViewTracking.enabled,
    samplingRate,
    slowThreshold
  };
}

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function stopMeasureReactNodeViewRendered({
  nodeTypeName,
  dispatchAnalyticsEvent,
  samplingRate,
  slowThreshold
}) {
  stopMeasure(`🦉${nodeTypeName}::ReactNodeView`, duration => {
    if (++nodeViewRenderedEventsCounter % samplingRate === 0 && duration > slowThreshold) {
      dispatchAnalyticsEvent({
        action: ACTION.REACT_NODEVIEW_RENDERED,
        actionSubject: ACTION_SUBJECT.EDITOR,
        eventType: EVENT_TYPE.OPERATIONAL,
        attributes: {
          node: nodeTypeName,
          duration
        }
      });
    }
  });
}
// eslint-disable-next-line @atlaskit/editor/no-re-export
export { startMeasureReactNodeViewRendered } from './startMeasureReactNodeViewRendered';