"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 _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");

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', _router.poststdbgRouter).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);
  });
  const ip = _internalIp.default.v4.sync();

  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);
    });
  });

  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);
  });
}