function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import { getType } from "../../../../util";
import { EXPOSURE_API_EVENT } from "../type";
import { safeStringify } from "../util";
export var EventCenter = /*#__PURE__*/function () {
  // 日志服务实例

  function EventCenter(_ref) {
    var logger = _ref.logger;
    _classCallCheck(this, EventCenter);
    _defineProperty(this, "activeEvents", new Map());
    // key: eventId, value: startTime
    _defineProperty(this, "heartbeatIntervalId", null);
    // 心跳定时器ID
    _defineProperty(this, "HEARTBEAT_INTERVAL", 5000);
    // 心跳间隔时间（毫秒）
    _defineProperty(this, "uniqueId", 0);
    // 唯一ID 自增
    _defineProperty(this, "logger", void 0);
    this.logger = logger;
  }

  /**
   * 注册事件
   * @param {string} functionName 函数名称
   * @returns {string} 返回事件起始ID
   */
  _createClass(EventCenter, [{
    key: "registerEvent",
    value: function registerEvent(functionName, sessionData) {
      // 构建事件起始ID
      var startId = this.buildId(functionName, 'start');
      var type = this.getEventName(functionName, 'start');
      // 将当前时间戳设置为活动事件的起始时间
      this.activeEvents.set(startId, Date.now());

      // 启动心跳检测
      this.startHeartbeat();
      // 发送日志，记录事件起始信息
      this.sendLog(type, {
        eventName: startId,
        sessionData: sessionData
      });
      return startId;
    }

    /**
     * 结束事件
     * @param startId 事件起始ID
     * @returns
     */
  }, {
    key: "endEvent",
    value: function endEvent(startId, extra) {
      // 如果活动事件中不存在该起始ID，则直接返回
      if (!this.activeEvents.has(startId)) return;
      // 获取起始时间
      var startTime = this.activeEvents.get(startId);
      // 从活动事件中删除该起始ID
      this.activeEvents.delete(startId);
      var type = this.getEventNameFromStart(startId, 'end');

      // 发送日志，记录事件结束信息
      this.sendLog(type, _objectSpread({
        eventName: this.buildIdFromStart(startId, 'end'),
        startTime: startTime,
        endTime: Date.now()
      }, extra || {}));
      if (extra && getType(extra) !== 'object') {
        this.sendLog('data_error', {
          msg: safeStringify(extra)
        });
      }

      // 如果活动事件数量为0，则停止心跳
      if (this.activeEvents.size === 0) this.stopHeartbeat();
    }

    /**
     * Cancels a single active event and reports it as an ended event with canceled=true.
     * This is used when the mount flow is terminated early (for example, on destroy or abnormal exit).
     */
  }, {
    key: "cancelEvent",
    value: function cancelEvent(startId, extra) {
      if (!this.activeEvents.has(startId)) return;
      var startTime = this.activeEvents.get(startId);
      this.activeEvents.delete(startId);
      var type = this.getEventNameFromStart(startId, 'end');
      this.sendLog(type, _objectSpread({
        eventName: this.buildIdFromStart(startId, 'end'),
        startTime: startTime,
        endTime: Date.now(),
        canceled: true
      }, extra || {}));
      if (this.activeEvents.size === 0) this.stopHeartbeat();
    }

    /**
     * Cancels all active events whose event id starts with the given prefix.
     * For example, prefix 'mount' will cancel events like mount_1_start.
     */
  }, {
    key: "cancelByPrefix",
    value: function cancelByPrefix(prefix, extra) {
      var _this = this;
      var ids = Array.from(this.activeEvents.keys()).filter(function (id) {
        return id.startsWith(prefix);
      });
      ids.forEach(function (id) {
        return _this.cancelEvent(id, extra);
      });
    }
  }, {
    key: "startHeartbeat",
    value: function startHeartbeat() {
      var _this2 = this;
      if (this.heartbeatIntervalId) return;
      this.heartbeatIntervalId = setInterval(function () {
        if (_this2.activeEvents.size === 0) {
          _this2.stopHeartbeat();
          return;
        }
        _this2.sendHeartbeat();
      }, this.HEARTBEAT_INTERVAL);
    }
  }, {
    key: "stopHeartbeat",
    value: function stopHeartbeat() {
      if (this.heartbeatIntervalId === null) return;
      clearInterval(this.heartbeatIntervalId);
      this.heartbeatIntervalId = null;
    }
  }, {
    key: "sendHeartbeat",
    value: function sendHeartbeat() {
      var actionNames = Array.from(this.activeEvents.entries()).map(function (_ref2) {
        var _ref3 = _slicedToArray(_ref2, 2),
          id = _ref3[0],
          startTime = _ref3[1];
        return {
          eventName: id,
          startTime: startTime
        };
      });
      this.sendLog('heart_beat', {
        actionNames: safeStringify(actionNames)
      });
    }
  }, {
    key: "sendLog",
    value: function sendLog(type, payload) {
      /**
       *当前使用以下事件映射，目前没有遗漏
       * mount_start
       * mount_end
       * submitPayment_start
       * submitPayment_end
       * validateFields_start
       * validateFields_end
       * destroy_start
       * destroy_end
       */
      //TODO: 后续需要移除映射，在执行入口埋点
      var titleMap = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, "".concat(EXPOSURE_API_EVENT.MOUNT, "_start"), 'sdk_event_mount'), "".concat(EXPOSURE_API_EVENT.MOUNT, "_end"), 'sdk_event_mount_end'), "".concat(EXPOSURE_API_EVENT.SUBMITPAYMENT, "_start"), 'sdk_event_submitPay'), "".concat(EXPOSURE_API_EVENT.SUBMITPAYMENT, "_end"), 'sdk_event_payment_end'), "".concat(EXPOSURE_API_EVENT.VALIDATAFIELDS, "_start"), 'sdk_event_validateFields'), "".concat(EXPOSURE_API_EVENT.VALIDATAFIELDS, "_end"), 'sdk_event_validateFields_end'), "".concat(EXPOSURE_API_EVENT.DESTORY, "_start"), 'sdk_event_apiOnDestroy'), "".concat(EXPOSURE_API_EVENT.DESTORY, "_end"), 'sdk_event_apiOnDestroy_end'), "heart_beat", 'sdk_element_handleHeartBeat'), "data_error", 'sdk_element_callback_error');
      var title = titleMap[type];
      if (!title) return;
      this.logger.logInfo({
        title: title
      }, _objectSpread({
        actionName: type
      }, payload));
    }
  }, {
    key: "buildId",
    value: function buildId(fn, suffix) {
      return "".concat(fn, "_").concat(++this.uniqueId, "_").concat(suffix);
    }

    // 通过fn生成埋点事件名，fn=mount，如mount_start
  }, {
    key: "getEventName",
    value: function getEventName(fn, suffix) {
      return "".concat(fn, "_").concat(suffix);
    }
  }, {
    key: "buildIdFromStart",
    value: function buildIdFromStart(startId, suffix) {
      return startId.replace(/_start$/, "_".concat(suffix));
    }

    // 通过startId生成埋点事件名，如mount_1_start --> mount_end，和生成规则一一对应
  }, {
    key: "getEventNameFromStart",
    value: function getEventNameFromStart(startId, suffix) {
      return startId.replace(/_.+_/i, '_').replace(/_start$/, "_".concat(suffix));
    }
  }]);
  return EventCenter;
}();