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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (_e) { function e(_x) { return _e.apply(this, arguments); } e.toString = function () { return _e.toString(); }; return e; }(function (e) { throw e; }), f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function (_e2) { function e(_x2) { return _e2.apply(this, arguments); } e.toString = function () { return _e2.toString(); }; return e; }(function (e) { didErr = true; err = e; }), f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 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 { ServiceProvider } from '..';
/**
 * Bus 埋点内容定义
 */
export var BusLogEventEnum = /*#__PURE__*/function (BusLogEventEnum) {
  BusLogEventEnum["sdk_event_busPublishMessage"] = "sdk_event_busPublishMessage";
  BusLogEventEnum["sdk_event_busPublishCallback"] = "sdk_event_busPublishCallback";
  BusLogEventEnum["sdk_event_busIsSubscribe"] = "sdk_event_busIsSubscribe";
  BusLogEventEnum["sdk_event_busSubscribe"] = "sdk_event_busSubscribe";
  BusLogEventEnum["sdk_event_busUnsubscribe"] = "sdk_event_busUnsubscribe";
  BusLogEventEnum["sdk_event_busClear"] = "sdk_event_busClear";
  BusLogEventEnum["sdk_event_busAddInterceptor"] = "sdk_event_busAddInterceptor";
  BusLogEventEnum["sdk_error_busPublishUnsubscribeError"] = "sdk_error_busPublishUnsubscribeError";
  BusLogEventEnum["sdk_error_busPublishError"] = "sdk_error_busPublishError";
  BusLogEventEnum["sdk_error_busPublishNoResult"] = "sdk_error_busPublishNoResult";
  return BusLogEventEnum;
}({});

/**
 * 扩展协议可序列化的消息定义
 */
export var BusMessage = /*#__PURE__*/function () {
  function BusMessage(action, data) {
    _classCallCheck(this, BusMessage);
    _defineProperty(this, "action", void 0);
    _defineProperty(this, "data", void 0);
    _defineProperty(this, "jsonData", null);
    this.action = action;
    this.data = data;
  }
  _createClass(BusMessage, [{
    key: "getAction",
    value: function getAction() {
      return this.action;
    }
  }, {
    key: "getData",
    value: function getData() {
      return this.data;
    }
  }, {
    key: "isJSONData",
    value: function isJSONData() {
      this.parseJSONData();
      return this.jsonData !== null;
    }
  }, {
    key: "getJSONObject",
    value: function getJSONObject() {
      var _this$jsonData;
      this.parseJSONData();
      return (_this$jsonData = this.jsonData) !== null && _this$jsonData !== void 0 ? _this$jsonData : {};
    }
  }, {
    key: "parseJSONData",
    value: function parseJSONData() {
      if (this.jsonData === null) {
        try {
          this.jsonData = JSON.parse(this.data);
        } catch (e) {
          // handle error if JSON parsing fails
          this.jsonData = null;
        }
      }
    }
  }, {
    key: "result",
    value: function result(_result) {
      return new BusMessage(this.action, JSON.stringify(_result));
    }
  }]);
  return BusMessage;
}();
/**
 *  扩展总线可选的Context参数，在Web端用于实时回调
 */
export var BusContext = /*#__PURE__*/function () {
  function BusContext(callback) {
    _classCallCheck(this, BusContext);
    _defineProperty(this, "callback", void 0);
    this.callback = callback;
  }
  _createClass(BusContext, [{
    key: "onCallBack",
    value: function onCallBack(message) {
      if (this.callback) {
        this.callback(message);
      }
    }
  }]);
  return BusContext;
}();

/**
 * 扩展能力的能力定义，基于此协议实现扩展能力
 */
export var BusSubscriber = /*#__PURE__*/_createClass(function BusSubscriber() {
  _classCallCheck(this, BusSubscriber);
});

/**
 * 拦截器，可增加扩展性
 */

/**
 * 事件总线入口，支持的关系为：
 * 发送者 和 接收者的关系：   一对一，大多数场景，支持callback
 * 发送者 和 接收者的关系：   多对一， 设计上多一对，但是同一时间点，只会一个发送者，支持callback
 * 发送者 和 接收者的关系：   一对多，可能有，埋点多重上报？不需要callback，业务场景应该是一个广播场景
 */
export var BusManager = /*#__PURE__*/function () {
  function BusManager() {
    var instanceId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
    _classCallCheck(this, BusManager);
    // Instance Variable
    _defineProperty(this, "isDebug", true);
    _defineProperty(this, "instanceId", void 0);
    _defineProperty(this, "logger", void 0);
    this.instanceId = instanceId;
    this.logger = ServiceProvider.getInstance(this.instanceId).getService('Log');
  }
  _createClass(BusManager, [{
    key: "debugTrace",
    value: function debugTrace(enable) {
      this.isDebug = enable;
    }
  }, {
    key: "traceLog",
    value: function traceLog(title, optionalParams) {
      var report = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
      if (this.isDebug) {
        console.log([BusManager.TAG, title].concat(JSON.stringify(optionalParams)).join(BusManager._logSplit));
      }
      if (report && this.logger) {
        this.logger.logInfo({
          title: title
        }, _objectSpread({
          eventSource: 'sdk'
        }, optionalParams)).send();
      }
    }
  }, {
    key: "traceError",
    value: function traceError(title, optionalParams) {
      if (this.isDebug) {
        console.error([BusManager.TAG, title].concat(JSON.stringify(optionalParams)).join(BusManager._logSplit));
      }
      if (this.logger) {
        this.logger.logError({
          title: title
        }, _objectSpread({
          eventSource: 'sdk'
        }, optionalParams)).send();
      }
    }
  }, {
    key: "clear",
    value: function clear() {
      this.traceLog(BusLogEventEnum.sdk_event_busClear);
      BusManager.interceptors.length = 0;
      BusManager.subscribersMap.clear();
    }
  }, {
    key: "addInterceptor",
    value: function addInterceptor(interceptor) {
      this.traceLog(BusLogEventEnum.sdk_event_busAddInterceptor);
      if (!BusManager.interceptors.includes(interceptor)) {
        BusManager.interceptors.push(interceptor);
      }
    }
  }, {
    key: "publishForResult",
    value: function publishForResult(message, config) {
      var _this = this;
      var failed = true;
      return new Promise(function (resolve, reject) {
        var _config$timeoutMs;
        _this.publish(message, function (result) {
          failed = false;
          resolve(result);
        });
        setTimeout(function () {
          if (failed) {
            _this.traceError(BusLogEventEnum.sdk_error_busPublishNoResult, {
              actionName: message.getAction()
            });
            if ((config === null || config === void 0 ? void 0 : config.fallback) !== null) {
              resolve(message.result(config === null || config === void 0 ? void 0 : config.fallback));
            } else {
              reject('publish timeout');
            }
          }
        }, (_config$timeoutMs = config === null || config === void 0 ? void 0 : config.timeoutMs) !== null && _config$timeoutMs !== void 0 ? _config$timeoutMs : 2000);
      });
    }
  }, {
    key: "publish",
    value: function publish(message, callback) {
      var _this2 = this;
      var _callBack = function _callBack(result) {
        _this2.traceLog(BusLogEventEnum.sdk_event_busPublishCallback, {
          actionName: message.getAction(),
          instanceId: _this2.instanceId
        });
        if (callback) {
          callback(result);
        }
      };
      var context = new BusContext(_callBack);
      var actionName = this.instanceId ? BusManager.getInstanceActionName(message.getAction(), this.instanceId) : message.getAction();
      var subscribers = BusManager.subscribersMap.get(actionName);
      this.traceLog(BusLogEventEnum.sdk_event_busPublishMessage, {
        actionName: message.getAction(),
        instanceId: this.instanceId
      });
      if (!subscribers && this.instanceId) {
        // 如果没有找到特定实例的订阅者，尝试查找通用订阅者
        subscribers = BusManager.subscribersMap.get(message.getAction());
      }
      if (subscribers) {
        var _iterator = _createForOfIteratorHelper(subscribers),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var subscriber = _step.value;
            try {
              subscriber.onMessage(context, message);
            } catch (e) {
              this.traceError(BusLogEventEnum.sdk_error_busPublishError, {
                actionName: message.getAction(),
                instanceId: this.instanceId,
                errorMessage: e
              });
              var _iterator2 = _createForOfIteratorHelper(BusManager.interceptors),
                _step2;
              try {
                for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                  var interceptor = _step2.value;
                  interceptor === null || interceptor === void 0 || interceptor.onPublishException(message, e);
                }
              } catch (err) {
                _iterator2.e(err);
              } finally {
                _iterator2.f();
              }
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      } else {
        var handle = false;
        var _iterator3 = _createForOfIteratorHelper(BusManager.interceptors),
          _step3;
        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var _interceptor = _step3.value;
            handle = handle || (_interceptor === null || _interceptor === void 0 ? void 0 : _interceptor.onUnsubscribedAction(message.getAction()));
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
        if (handle) {
          this.publish(message, callback); // Re-publish the message
        } else {
          this.traceError(BusLogEventEnum.sdk_error_busPublishUnsubscribeError, {
            actionName: message.getAction(),
            instanceId: this.instanceId
          });
        }
      }
    }
  }, {
    key: "subscribe",
    value: function subscribe(subscriber) {
      this.traceLog(BusLogEventEnum.sdk_event_busSubscribe, {
        actionNames: subscriber.actionNames(),
        instanceId: this.instanceId
      });
      var _iterator4 = _createForOfIteratorHelper(subscriber.actionNames()),
        _step4;
      try {
        for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
          var _actionName = _step4.value;
          var key = this.instanceId ? BusManager.getInstanceActionName(_actionName, this.instanceId) : _actionName;
          if (!BusManager.subscribersMap.has(key)) {
            BusManager.subscribersMap.set(key, []);
          }
          var subscribers = BusManager.subscribersMap.get(key);
          if (subscribers && !subscribers.includes(subscriber)) {
            subscribers.push(subscriber);
          }
        }
      } catch (err) {
        _iterator4.e(err);
      } finally {
        _iterator4.f();
      }
    }
  }, {
    key: "unsubscribe",
    value: function unsubscribe(subscriber) {
      this.traceLog(BusLogEventEnum.sdk_event_busUnsubscribe, {
        actionNames: subscriber.actionNames(),
        instanceId: this.instanceId
      });
      var _iterator5 = _createForOfIteratorHelper(subscriber.actionNames()),
        _step5;
      try {
        for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
          var _actionName2 = _step5.value;
          var key = this.instanceId ? BusManager.getInstanceActionName(_actionName2, this.instanceId) : _actionName2;
          var subscribers = BusManager.subscribersMap.get(key);
          if (subscribers) {
            var index = subscribers.indexOf(subscriber);
            if (index !== -1) {
              subscribers.splice(index, 1);
            }
            if (subscribers.length === 0) {
              BusManager.subscribersMap.delete(key);
            }
          }
        }
      } catch (err) {
        _iterator5.e(err);
      } finally {
        _iterator5.f();
      }
    }
  }, {
    key: "isSubscribed",
    value: function isSubscribed(actionName) {
      var key = this.instanceId ? BusManager.getInstanceActionName(actionName, this.instanceId) : actionName;
      var subscribers = BusManager.subscribersMap.get(key);
      if (!subscribers && this.instanceId) {
        // 如果没有找到特定实例的订阅者，检查是否有通用订阅者
        subscribers = BusManager.subscribersMap.get(actionName);
      }
      if (subscribers && subscribers.length > 0) {
        this.traceLog(BusLogEventEnum.sdk_event_busIsSubscribe, {
          actionName: actionName,
          instanceId: this.instanceId,
          processResult: true
        });
        return true;
      }
      var handle = false;
      var _iterator6 = _createForOfIteratorHelper(BusManager.interceptors),
        _step6;
      try {
        for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
          var interceptor = _step6.value;
          handle = handle || interceptor.onUnsubscribedAction(actionName);
        }
      } catch (err) {
        _iterator6.e(err);
      } finally {
        _iterator6.f();
      }
      if (handle) {
        return BusManager.subscribersMap.has(key);
      }
      this.traceLog(BusLogEventEnum.sdk_event_busIsSubscribe, {
        actionName: actionName,
        instanceId: this.instanceId,
        processResult: false
      });
      return false;
    }
  }], [{
    key: "getInstanceActionName",
    value: function getInstanceActionName(actionName, instanceId) {
      return "".concat(actionName, "@").concat(instanceId);
    }
  }]);
  return BusManager;
}();
// Static Variable
_defineProperty(BusManager, "interceptors", []);
_defineProperty(BusManager, "subscribersMap", new Map());
_defineProperty(BusManager, "TAG", 'BusManager');
_defineProperty(BusManager, "_logSplit", ' , ');