import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../../tslib.es6-848120af.js';
import { isTestEnvInPixui } from '../env.mjs';
import { getGameletPixuiFrame } from '../gamelet.mjs';

// 加载 uid 和 aid
var initUserData = function initUserData(aegis) {
  return __awaiter(void 0, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var _a, _getGameletPixuiFrame, GameletAPI, _yield$GameletAPI$get, sOpenId, openID, thisAid, lastAid, aid;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          // eslint-disable-next-line @typescript-eslint/naming-convention
          _getGameletPixuiFrame = getGameletPixuiFrame(), GameletAPI = _getGameletPixuiFrame.GameletAPI;
          _context.next = 1;
          return GameletAPI.getUserData();
        case 1:
          _yield$GameletAPI$get = _context.sent;
          sOpenId = _yield$GameletAPI$get.sOpenId;
          openID = _yield$GameletAPI$get.openID;
          thisAid = (_a = window.localStorage) === null || _a === void 0 ? void 0 : _a.getItem('AEGIS_ID');
          if (!GameletAPI.canUsePlatformAPI()) {
            _context.next = 3;
            break;
          }
          _context.next = 2;
          return GameletAPI.readCookie('AEGIS_ID');
        case 2:
          lastAid = _context.sent;
        case 3:
          aid = lastAid || thisAid;
          if (!lastAid && thisAid) {
            GameletAPI.writeCookie('AEGIS_ID', thisAid);
          }
          if (sOpenId || openID) {
            aegis.setConfig({
              uid: sOpenId || openID
            });
          }
          if (aid) {
            aegis.setConfig({
              aid: aid
            });
          }
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
};
// URL 处理，需要自定义，不同游戏不太一样
var urlHandler = function urlHandler() {
  var _a;
  // 原本的获取方式： let url: string = this.config.pageUrl || location.href || '';
  var path = location.pathname.replace('/index.html', '');
  var search = ((_a = location.search) === null || _a === void 0 ? void 0 : _a.indexOf('?')) > -1 || !location.search ? location.search || '' : "?".concat(location.search);
  // 上报时获取最后 2 个路径，如 /xxxx/Client/Saved/Gamelet/extract/5535/gamelet5535social_bin/app/feedsHome，只会取到 /app/feedsHome
  var reportPath = "/".concat(path.split('/').filter(function (p) {
    return p !== '';
  }).slice(-2).join('/'));
  return reportPath + search;
};
// 返回码处理，一般可以复用
var retCodeHandler = function retCodeHandler(obj, _url, _xhr, _payload) {
  var returnCode = "".concat(((obj === null || obj === void 0 ? void 0 : obj.returnCode) || (obj === null || obj === void 0 ? void 0 : obj.code) || (obj === null || obj === void 0 ? void 0 : obj.retcode) || (obj === null || obj === void 0 ? void 0 : obj.errcode) || 'unknown').toString());
  return {
    code: returnCode,
    isErr: returnCode !== '0' && returnCode !== 'unknown'
  };
};
function isTestEnvironment() {
  return isTestEnvInPixui();
}
function initAegis(options) {
  var _a;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var env, aegis;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          // 获取环境
          env = isTestEnvironment() ? options.Aegis.environment.TEST : options.Aegis.environment.PROD;
          if (!window.mAegis) {
            _context2.next = 1;
            break;
          }
          return _context2.abrupt("return", window.mAegis);
        case 1:
          (_a = options === null || options === void 0 ? void 0 : options.setupPolyfills) === null || _a === void 0 ? void 0 : _a.call(options);
          // 初始化实例
          aegis = new options.Aegis({
            id: options.aegisKey,
            env: env,
            plugin: {
              session: true,
              spa: true,
              api: {
                apiDetail: true,
                injectTraceHeader: 'traceparent',
                reqHeaders: ['traceparent'],
                retCodeHandler: retCodeHandler
              },
              assetSpeed: true
            },
            reportImmediately: false,
            urlHandler: urlHandler,
            hostUrl: options.url
          });
          _context2.next = 2;
          return initUserData(aegis);
        case 2:
          _context2.next = 3;
          return aegis.ready();
        case 3:
          window.mAegis = aegis;
          return _context2.abrupt("return", aegis);
        case 4:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

export { initAegis };
