"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ReportManager = void 0;
var _momentTimezone = _interopRequireDefault(require("moment-timezone"));
var _util = require("./util");
var _metrics = require("./metrics");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Any modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */ /*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
const REPORT_VERSION = 1;
class ReportManager {
  constructor(report) {
    _defineProperty(this, "report", void 0);
    this.report = report || ReportManager.createReport();
  }
  static createReport() {
    return {
      reportVersion: REPORT_VERSION
    };
  }
  clearReport() {
    this.report = ReportManager.createReport();
  }
  isReportEmpty() {
    const {
      uiStatsMetrics,
      userAgent,
      application_usage: appUsage
    } = this.report;
    const noUiStats = !uiStatsMetrics || Object.keys(uiStatsMetrics).length === 0;
    const noUserAgent = !userAgent || Object.keys(userAgent).length === 0;
    const noAppUsage = !appUsage || Object.keys(appUsage).length === 0;
    return noUiStats && noUserAgent && noAppUsage;
  }
  incrementStats(count, stats) {
    const {
      min = 0,
      max = 0,
      sum = 0
    } = stats || {};
    const newMin = Math.min(min, count);
    const newMax = Math.max(max, count);
    const newAvg = newMin + newMax / 2;
    const newSum = sum + count;
    return {
      min: newMin,
      max: newMax,
      avg: newAvg,
      sum: newSum
    };
  }
  assignReports(newMetrics) {
    (0, _util.wrapArray)(newMetrics).forEach(newMetric => this.assignReport(this.report, newMetric));
    return {
      report: this.report
    };
  }
  static createMetricKey(metric) {
    switch (metric.type) {
      case _metrics.METRIC_TYPE.USER_AGENT:
        {
          const {
            appName,
            type
          } = metric;
          return `${appName}-${type}`;
        }
      case _metrics.METRIC_TYPE.CLICK:
      case _metrics.METRIC_TYPE.LOADED:
      case _metrics.METRIC_TYPE.COUNT:
        {
          const {
            appName,
            eventName,
            type
          } = metric;
          return `${appName}-${type}-${eventName}`;
        }
      case _metrics.METRIC_TYPE.APPLICATION_USAGE:
        return metric.appId;
      default:
        throw new _util.UnreachableCaseError(metric);
    }
  }
  assignReport(report, metric) {
    const key = ReportManager.createMetricKey(metric);
    switch (metric.type) {
      case _metrics.METRIC_TYPE.USER_AGENT:
        {
          const {
            appName,
            type,
            userAgent
          } = metric;
          if (userAgent) {
            report.userAgent = {
              [key]: {
                key,
                appName,
                type,
                userAgent: metric.userAgent
              }
            };
          }
          return;
        }
      case _metrics.METRIC_TYPE.CLICK:
      case _metrics.METRIC_TYPE.LOADED:
      case _metrics.METRIC_TYPE.COUNT:
        {
          const {
            appName,
            type,
            eventName,
            count
          } = metric;
          report.uiStatsMetrics = report.uiStatsMetrics || {};
          const existingStats = (report.uiStatsMetrics[key] || {}).stats;
          report.uiStatsMetrics[key] = {
            key,
            appName,
            eventName,
            type,
            stats: this.incrementStats(count, existingStats)
          };
          return;
        }
      case _metrics.METRIC_TYPE.APPLICATION_USAGE:
        const {
          numberOfClicks,
          startTime
        } = metric;
        const minutesOnScreen = (0, _momentTimezone.default)().diff(startTime, 'minutes', true);
        report.application_usage = report.application_usage || {};
        const appExistingData = report.application_usage[key] || {
          minutesOnScreen: 0,
          numberOfClicks: 0
        };
        report.application_usage[key] = {
          minutesOnScreen: appExistingData.minutesOnScreen + minutesOnScreen,
          numberOfClicks: appExistingData.numberOfClicks + numberOfClicks
        };
        break;
      default:
        throw new _util.UnreachableCaseError(metric);
    }
  }
}
exports.ReportManager = ReportManager;
_defineProperty(ReportManager, "REPORT_VERSION", REPORT_VERSION);