"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getErrorEventRate = getErrorEventRate;
var _document_type = require("../../../../common/document_type");
var _rollup = require("../../../../common/rollup");
var _fetch_timeseries = require("./fetch_timeseries");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

async function getErrorEventRate({
  apmEventClient,
  start,
  end,
  intervalString,
  bucketSize,
  filter
}) {
  const bucketSizeInMinutes = bucketSize / 60;
  const rangeInMinutes = (end - start) / 1000 / 60;
  return (await (0, _fetch_timeseries.fetchSeries)({
    apmEventClient,
    start,
    end,
    operationName: 'assistant_get_error_event_rate',
    unit: 'rpm',
    documentType: _document_type.ApmDocumentType.ErrorEvent,
    rollupInterval: _rollup.RollupInterval.None,
    intervalString,
    filter,
    aggs: {
      value: {
        bucket_script: {
          buckets_path: {
            count: '_count'
          },
          script: {
            lang: 'painless',
            params: {
              bucketSizeInMinutes
            },
            source: 'params.count / params.bucketSizeInMinutes'
          }
        }
      }
    }
  })).map(fetchedSerie => {
    return {
      ...fetchedSerie,
      value: fetchedSerie.value !== null ? fetchedSerie.value / rangeInMinutes : null,
      data: fetchedSerie.data.map(bucket => {
        var _bucket$value;
        return {
          x: bucket.key,
          y: (_bucket$value = bucket.value) === null || _bucket$value === void 0 ? void 0 : _bucket$value.value
        };
      })
    };
  });
}