"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Reporter = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _util = require("./util");
var _metrics = require("./metrics");
var _storage = require("./storage");
var _report = require("./report");
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

class Reporter {
  constructor(config) {
    (0, _defineProperty2.default)(this, "checkInterval", void 0);
    (0, _defineProperty2.default)(this, "interval", void 0);
    (0, _defineProperty2.default)(this, "http", void 0);
    (0, _defineProperty2.default)(this, "reportManager", void 0);
    (0, _defineProperty2.default)(this, "storageManager", void 0);
    (0, _defineProperty2.default)(this, "debug", void 0);
    (0, _defineProperty2.default)(this, "retryCount", 0);
    (0, _defineProperty2.default)(this, "maxRetries", 3);
    (0, _defineProperty2.default)(this, "start", () => {
      if (!this.interval) {
        this.interval = setTimeout(() => {
          this.interval = undefined;
          this.sendReports();
        }, this.checkInterval);
      }
    });
    (0, _defineProperty2.default)(this, "reportUiCounter", (appName, type, eventNames, count) => {
      const metrics = (0, _util.wrapArray)(eventNames).map(eventName => {
        this.log(`${type} Metric -> (${appName}:${eventName}):`);
        const report = (0, _metrics.createUiCounterMetric)({
          type,
          appName,
          eventName,
          count
        });
        this.log(report);
        return report;
      });
      this.saveToReport(metrics);
    });
    (0, _defineProperty2.default)(this, "reportUserAgent", appName => {
      this.log(`Reporting user-agent.`);
      const report = (0, _metrics.trackUsageAgent)(appName);
      this.saveToReport([report]);
    });
    (0, _defineProperty2.default)(this, "sendReports", async () => {
      if (!this.reportManager.isReportEmpty()) {
        try {
          await this.http(this.reportManager.report);
          this.flushReport();
        } catch (err) {
          this.log(`Error Sending Metrics Report ${err}`);
          this.retryCount = this.retryCount + 1;
          const versionMismatch = this.reportManager.report.reportVersion !== _report.ReportManager.REPORT_VERSION;
          if (versionMismatch || this.retryCount > this.maxRetries) {
            this.flushReport();
          }
        }
      }
      this.start();
    });
    const {
      http,
      storage,
      debug,
      checkInterval = 90000,
      storageKey = 'analytics'
    } = config;
    this.http = http;
    this.checkInterval = checkInterval;
    this.storageManager = new _storage.ReportStorageManager(storageKey, storage);
    const storedReport = this.storageManager.get();
    this.reportManager = new _report.ReportManager(storedReport);
    this.debug = !!debug;
  }
  saveToReport(newMetrics) {
    this.reportManager.assignReports(newMetrics);
    this.storageManager.store(this.reportManager.report);
  }
  flushReport() {
    this.retryCount = 0;
    this.reportManager.clearReport();
    this.storageManager.store(this.reportManager.report);
  }
  log(message) {
    if (this.debug) {
      // eslint-disable-next-line no-console
      console.debug(message);
    }
  }
  reportApplicationUsage(appUsageReport) {
    this.log(`Reporting application usage for ${appUsageReport.appId}, ${appUsageReport.viewId}`);
    this.saveToReport([appUsageReport]);
  }
}
exports.Reporter = Reporter;