"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.initServer = initServer;_Object$defineProperty(exports, "notifyUpdate", { enumerable: true, get: function () {return _notify.default;} });exports.stopServer = stopServer;var _now = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/date/now"));var _keys = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/keys"));var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));var _koa = _interopRequireDefault(require("koa"));
var _path = _interopRequireDefault(require("path"));
var _koaStatic = _interopRequireDefault(require("koa-static"));
var _http = _interopRequireDefault(require("http"));
var _internalIp = _interopRequireDefault(require("internal-ip"));
var _koaBodyparser = _interopRequireDefault(require("koa-bodyparser"));
var _qrcode = _interopRequireDefault(require("qrcode"));
var _koaRouter = _interopRequireDefault(require("koa-router"));
var _portfinder = _interopRequireDefault(require("portfinder"));
var _router = require("./router.js");
var _logger = require("./logger.js");
var _recordClient = require("./record-client.js");
var _notify = _interopRequireDefault(require("./notify.js"));
var _wsserver = require("./wsserver.js");
var _index = require("./adb/index.js");
var _requestIde = require("../utils/requestIde.js");
var _os = _interopRequireDefault(require("os"));
const compress = require('koa-compress');
let server = null;
async function initServer(args) {
  const app = new _koa.default();
  const route = new _koaRouter.default();
  const port = await _portfinder.default.getPortPromise();
  app.use((0, _koaBodyparser.default)());
  app.use(compress());

  app.use((0, _koaStatic.default)(_path.default.resolve(__dirname, './client'), {
    maxAge: 2592000000, // 缓存时间为一年
    gzip: true,
    setHeaders: (res) => {
      res.setHeader('Cache-Control', 'public, max-age=2592000');
      res.setHeader('Expires', new Date((0, _now.default)() + 2592000000).toUTCString());
    }
  }));

  app.use(_logger.logger);
  app.use(route.get('/', _router.indexRouter).routes());
  app.use(route.get('/bundle', _router.bundleRouter).routes());
  app.use(route.post('/poststdbg', (ctx) => (0, _router.poststdbgRouter)(ctx, args)).routes());
  app.use(route.get('/debug', _router.debugRouter).routes());
  server = _http.default.Server(app.callback());
  beforeStart(server, app, port);
  app.on('error', (err, ctx) => {
    console.error('server error', err);
  });
  let ip = _internalIp.default.v4.sync();

  //ip获取失败时重新判断
  if (!ip) {
    const nets = _os.default.networkInterfaces();
    let ipv4;

    for (const name of (0, _keys.default)(nets)) {
      for (const net of nets[name]) {
        if (net.family === 'IPv4' && !net.internal) {
          ipv4 = net.address;
          break;
        }
      }
      if (ipv4) break;
    }

    ip = ipv4;
  }

  const url = `http://${ip}:${port}`;
  // 下面的log不能随便改，否则cocos IDE预览会有问题
  server.listen(port, () => {
    console.log(`地址 ${url}`);
    console.log(`若二维码无法识别，可打开以上地址尝试~`);
    console.log('请确保手机与App Server处于相同网段！');
    _qrcode.default.toString(url, { type: 'terminal', small: true }, function (err, url) {
      if (err) {
        // Handle the error, e.g., log it or deal with it appropriately
        console.error('Failed to generate QR code:', err);
        return; // Early return to prevent further processing
      }
      console.log(url);
    });

    if (args.ide) {
      (0, _requestIde.fetchInfo)({
        url,
        port
      }, 'startDebug');
    }
  });

  // 监听进程终止信号
  process.on('SIGINT', handleShutdown);
  process.on('SIGTERM', handleShutdown);

  async function handleShutdown() {
    console.log('\n### App Server ### 服务器即将关闭');
    if (args.ide) {
      await (0, _requestIde.fetchInfo)({
        url,
        port
      }, 'stopDebug');
    }
    process.exit(0);
  }

  return url;
}
function stopServer() {
  return new _promise.default((resolve) => {
    if (!server) {
      resolve({ stopServerError: 'no server' });
      return;
    }
    try {
      server.close((data) => {
        resolve({ stopServerError: data });
      });
    } catch (err) {
      console.error(`### App Server ### 服务器关闭失败: ${err.message}`);
      resolve({ stopServerError: err });
      throw err;
    }
  });
}

async function beforeStart(server, app, port) {
  await (0, _wsserver.createSocketServer)(server, app);
  (0, _index.createADBDebugger)({
    pathClientLog: _recordClient.clientRecordPath,
    localReversePort: port
  }).then((data) => {
    app.context.adbDebugger = data;
  }).catch((err) => {
    console.error(err);
  });
}