"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getMobileStatsPeriods = getMobileStatsPeriods;
var _get_offset_in_ms = require("../../../common/utils/get_offset_in_ms");
var _get_mobile_sessions = require("./get_mobile_sessions");
var _get_mobile_http_requests = require("./get_mobile_http_requests");
var _get_mobile_crash_rate = require("./get_mobile_crash_rate");
/*
 * 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 getMobileStats({
  kuery,
  apmEventClient,
  serviceName,
  environment,
  start,
  end,
  offset
}) {
  var _crashes$currentPerio;
  const {
    startWithOffset,
    endWithOffset
  } = (0, _get_offset_in_ms.getOffsetInMs)({
    start,
    end,
    offset
  });
  const commonProps = {
    kuery,
    apmEventClient,
    serviceName,
    environment,
    start: startWithOffset,
    end: endWithOffset,
    offset
  };
  const [sessions, httpRequests, crashes] = await Promise.all([(0, _get_mobile_sessions.getMobileSessions)({
    ...commonProps
  }), (0, _get_mobile_http_requests.getMobileHttpRequests)({
    ...commonProps
  }), (0, _get_mobile_crash_rate.getMobileCrashRate)({
    ...commonProps
  })]);
  return {
    sessions: {
      value: sessions.currentPeriod.value,
      timeseries: sessions.currentPeriod.timeseries
    },
    requests: {
      value: httpRequests.currentPeriod.value,
      timeseries: httpRequests.currentPeriod.timeseries
    },
    crashRate: {
      value: sessions.currentPeriod.value ? ((_crashes$currentPerio = crashes.currentPeriod.value) !== null && _crashes$currentPerio !== void 0 ? _crashes$currentPerio : 0) / sessions.currentPeriod.value : 0,
      timeseries: crashes.currentPeriod.timeseries.map((bucket, i) => {
        var _bucket$y;
        const sessionValue = sessions.currentPeriod.timeseries[i].y;
        return {
          x: bucket.x,
          y: sessionValue ? ((_bucket$y = bucket.y) !== null && _bucket$y !== void 0 ? _bucket$y : 0) / sessionValue : 0
        };
      })
    }
  };
}
async function getMobileStatsPeriods({
  kuery,
  apmEventClient,
  serviceName,
  environment,
  start,
  end,
  offset
}) {
  const commonProps = {
    kuery,
    apmEventClient,
    serviceName,
    environment,
    start,
    end
  };
  const currentPeriodPromise = getMobileStats({
    ...commonProps
  });
  const previousPeriodPromise = offset ? getMobileStats({
    ...commonProps,
    offset
  }) : {
    sessions: {
      timeseries: [],
      value: null
    },
    requests: {
      timeseries: [],
      value: null
    },
    crashRate: {
      timeseries: [],
      value: null
    }
  };
  const [currentPeriod, previousPeriod] = await Promise.all([currentPeriodPromise, previousPeriodPromise]);
  return {
    currentPeriod,
    previousPeriod
  };
}