"use strict";var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");_Object$defineProperty(exports, "__esModule", { value: true });exports.logger = logger;var _path = _interopRequireDefault(require("path"));
var _index = require("../cli-shared-utils/index.js");
var _recordClient = require("./record-client.js");


/**
 * 记录最新的用户进入的请求
 */
async function logger(context, next) {
  try {
    const { sn, clientIp, linkMode, serverIp } = (0, _recordClient.getClientFromRequest)(context.request);
    const addrClient = clientIp;
    const addrServer = serverIp;

    let client = {
      sn: sn,
      ip: addrClient,
      port: _recordClient.CLIENT_PORT
    };

    switch (linkMode) {
      case _recordClient.LINK_MODE.WIFI:
        console.info(`### App Server ### 记录从${addrClient}进入的HTTP请求`);
        (0, _recordClient.recordClient)(_recordClient.clientRecordPath, client);
        break;
      case _recordClient.LINK_MODE.ADB:
        // ADB模式下需要先读取连接时记录的信息
        client = (0, _recordClient.getRecordClient)(_recordClient.clientRecordPath, sn, addrClient);
        if (!client) {
          const realSN = context.adbDebugger.emulators.get(sn);
          console.info(`### App Server ### 通过（${sn}）查找到设备${realSN}`);
          client = (0, _recordClient.getRecordClient)(_recordClient.clientRecordPath, realSN, clientIp);
        }
        if (client) {
          console.info(`### App Server ### 记录从设备(${sn})进入的HTTP请求`);
          (0, _recordClient.recordClient)(_recordClient.clientRecordPath, client);
        } else {
          console.info(`### App Server ### ：记录设备(${sn})失败`);
        }
        break;
    }

    if (addrClient !== addrServer && (addrClient !== '127.0.0.1' || linkMode === _recordClient.LINK_MODE.ADB)) {
      (0, _index.info)(`### App Server ### 写入到client.json，${addrClient}的HTTP请求`);
      _index.fs.outputJsonSync(_path.default.resolve(_index.projectPath, 'client.json'), {
        client: addrClient,
        timestamp: new Date()
      });
    }
  } catch (err) {
    (0, _index.error)(`### App Server ### 记录log出错: ${err.message}`);
  }
  await next();
}