"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.trackEvent = trackEvent;
exports.aliasUser = aliasUser;
exports.trackEventWithEnv = trackEventWithEnv;

var _index = _interopRequireDefault(require("./analytics/index"));

var _tracks = _interopRequireDefault(require("./analytics/clients/tracks"));

var _token = _interopRequireDefault(require("./token"));

var _config = _interopRequireDefault(require("../../config/config.json"));

var _env = _interopRequireDefault(require("./env"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * External dependencies
 */
const debug = require('debug')('@automattic/vip:analytics');
/**
 * Internal dependencies
 */


let analytics = null;

async function init() {
  const uuid = await _token.default.uuid();
  const clients = {};
  const tracksUserType = _config.default.tracksUserType;
  const tracksEventPrefix = _config.default.tracksEventPrefix;

  if (tracksUserType && tracksEventPrefix) {
    clients.tracks = new _tracks.default(uuid, tracksUserType, tracksEventPrefix, _env.default);
  }

  analytics = new _index.default(clients);
  return analytics;
}

async function getInstance() {
  if (analytics) {
    return analytics;
  }

  analytics = init();
  return analytics;
}

async function trackEvent(...args) {
  await _token.default.uuid();

  try {
    const client = await getInstance();
    return client.trackEvent(...args);
  } catch (e) {
    debug('trackEvent() failed', e);
  }
}

async function aliasUser(vipUserId) {
  try {
    if (vipUserId) {
      await trackEvent('_alias_user', {
        ui: vipUserId,
        _ut: _config.default.tracksUserType,
        anonid: _token.default.uuid()
      });

      _token.default.setUuid(vipUserId);
    }
  } catch (e) {
    debug('aliasUser() failed', e);
  }
}

async function trackEventWithEnv(appId, envId, eventName, eventProps = {}) {
  return trackEvent(eventName, { ...eventProps,
    app_id: appId,
    env_id: envId
  });
}