import { isPerformanceAPIAvailable } from '../utils/performance/is-performance-api-available';
const measureMap = new Map();
export function startMeasure(measureName) {
  if (!isPerformanceAPIAvailable()) {
    return;
  }
  performance.mark(`${measureName}::start`);
  measureMap.set(measureName, performance.now());
}

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function stopMeasure(measureName, onMeasureComplete) {
  if (!isPerformanceAPIAvailable()) {
    return;
  }
  performance.mark(`${measureName}::end`);
  const start = onMeasureComplete ? measureMap.get(measureName) : undefined;
  try {
    performance.measure(measureName, `${measureName}::start`, `${measureName}::end`);
  } catch (error) {} finally {
    if (onMeasureComplete) {
      const entry = performance.getEntriesByName(measureName).pop();
      if (entry) {
        onMeasureComplete(entry.duration, entry.startTime);
      } else if (start) {
        onMeasureComplete(performance.now() - start, start);
      }
    }
    clearMeasure(measureName);
  }
}

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function clearMeasure(measureName) {
  if (!isPerformanceAPIAvailable()) {
    return;
  }
  measureMap.delete(measureName);
  performance.clearMarks(`${measureName}::start`);
  performance.clearMarks(`${measureName}::end`);
  performance.clearMeasures(measureName);
}

// eslint-disable-next-line @atlaskit/volt-strict-mode/no-multiple-exports
export function isMeasuring(measureName) {
  if (!isPerformanceAPIAvailable()) {
    return false;
  }
  return measureMap.get(measureName) !== undefined;
}