"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getMobileSessions = getMobileSessions;
var _common = require("@kbn/observability-plugin/common");
var _server = require("@kbn/observability-plugin/server");
var _offset_previous_period_coordinate = require("../../../common/utils/offset_previous_period_coordinate");
var _apm = require("../../../common/es_fields/apm");
var _environment_query = require("../../../common/utils/environment_query");
var _get_offset_in_ms = require("../../../common/utils/get_offset_in_ms");
var _get_bucket_size = require("../../../common/utils/get_bucket_size");
/*
 * 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 getSessionTimeseries({
  apmEventClient,
  serviceName,
  transactionName,
  environment,
  start,
  end,
  kuery,
  offset
}) {
  var _response$aggregation, _response$aggregation2, _response$aggregation3, _response$aggregation4;
  const {
    startWithOffset,
    endWithOffset
  } = (0, _get_offset_in_ms.getOffsetInMs)({
    start,
    end,
    offset
  });
  const {
    intervalString
  } = (0, _get_bucket_size.getBucketSize)({
    start: startWithOffset,
    end: endWithOffset,
    minBucketSize: 60
  });
  const aggs = {
    sessions: {
      cardinality: {
        field: _apm.SESSION_ID
      }
    }
  };
  const response = await apmEventClient.search('get_mobile_sessions', {
    apm: {
      events: [_common.ProcessorEvent.transaction]
    },
    body: {
      track_total_hits: false,
      size: 0,
      query: {
        bool: {
          filter: [{
            exists: {
              field: _apm.SESSION_ID
            }
          }, ...(0, _server.termQuery)(_apm.SERVICE_NAME, serviceName), ...(0, _server.termQuery)(_apm.TRANSACTION_NAME, transactionName), ...(0, _server.rangeQuery)(startWithOffset, endWithOffset), ...(0, _environment_query.environmentQuery)(environment), ...(0, _server.kqlQuery)(kuery)]
        }
      },
      aggs: {
        timeseries: {
          date_histogram: {
            field: '@timestamp',
            fixed_interval: intervalString,
            min_doc_count: 0,
            extended_bounds: {
              min: startWithOffset,
              max: endWithOffset
            }
          },
          aggs
        },
        ...aggs
      }
    }
  });
  const timeseries = (_response$aggregation = response === null || response === void 0 ? void 0 : (_response$aggregation2 = response.aggregations) === null || _response$aggregation2 === void 0 ? void 0 : _response$aggregation2.timeseries.buckets.map(bucket => {
    return {
      x: bucket.key,
      y: bucket.sessions.value
    };
  })) !== null && _response$aggregation !== void 0 ? _response$aggregation : [];
  return {
    timeseries,
    value: (_response$aggregation3 = response.aggregations) === null || _response$aggregation3 === void 0 ? void 0 : (_response$aggregation4 = _response$aggregation3.sessions) === null || _response$aggregation4 === void 0 ? void 0 : _response$aggregation4.value
  };
}
async function getMobileSessions({
  kuery,
  apmEventClient,
  serviceName,
  transactionName,
  environment,
  start,
  end,
  offset
}) {
  const options = {
    serviceName,
    transactionName,
    apmEventClient,
    kuery,
    environment
  };
  const currentPeriodPromise = getSessionTimeseries({
    ...options,
    start,
    end
  });
  const previousPeriodPromise = offset ? getSessionTimeseries({
    ...options,
    start,
    end,
    offset
  }) : {
    timeseries: [],
    value: null
  };
  const [currentPeriod, previousPeriod] = await Promise.all([currentPeriodPromise, previousPeriodPromise]);
  return {
    currentPeriod,
    previousPeriod: {
      timeseries: (0, _offset_previous_period_coordinate.offsetPreviousPeriodCoordinates)({
        currentPeriodTimeseries: currentPeriod.timeseries,
        previousPeriodTimeseries: previousPeriod.timeseries
      }),
      value: previousPeriod === null || previousPeriod === void 0 ? void 0 : previousPeriod.value
    }
  };
}