"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopServer = exports.startDebugServer = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const kill_port_1 = tslib_1.__importDefault(require("kill-port"));
const koa_1 = tslib_1.__importDefault(require("koa"));
const safe_1 = tslib_1.__importDefault(require("colors/safe"));
const client_1 = require("@/client");
const socket_server_1 = require("@/socket-server");
const log_1 = require("@/utils/log");
const db_1 = require("@/db");
const router_1 = require("@/router");
const config_1 = require("@/config");
const enum_1 = require("@/@types/enum");
const url_1 = require("@/utils/url");
const log = new log_1.Logger('debug-server', enum_1.WinstonColor.Yellow);
let server;
let socketServer;
/**
 * 开启调试服务
 */
const startDebugServer = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    log.info('start server argv: %j', global.debugAppArgv);
    const { host, port, env } = global.debugAppArgv;
    yield init();
    if (env === "hippy" /* Hippy */)
        showHippyGuide();
    const app = new koa_1.default();
    router_1.routeApp(app);
    server = app.listen(port, host, () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        log.info('start debug server success.');
        if (!config_1.config.isCluster) {
            const { startTunnel, startChrome } = yield Promise.resolve().then(() => tslib_1.__importStar(require('./child-process/index')));
            yield startTunnel();
            startChrome();
            const { startAdbProxy } = yield Promise.resolve().then(() => tslib_1.__importStar(require('./child-process/adb')));
            startAdbProxy();
        }
        socketServer = new socket_server_1.SocketServer(server);
        socketServer.start();
    }));
    server.on('close', () => {
        log.warn('debug server is closed.');
    });
    server.on('error', (e) => {
        log.error('launch debug server failed: %j', e);
    });
});
exports.startDebugServer = startDebugServer;
/**
 * 停止调试服务
 */
const stopServer = (exitProcess = false, ...arg) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _a;
    try {
        log.info('stopServer %j', arg);
        if (socketServer) {
            yield socketServer.close();
            socketServer = null;
        }
        if (server) {
            server.close();
            server = null;
        }
        if (exitProcess)
            process.exit(0);
    }
    catch (e) {
        log.error('stopServer error, %s', (_a = e) === null || _a === void 0 ? void 0 : _a.stack);
    }
});
exports.stopServer = stopServer;
/**
 * 服务初始化
 */
const init = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    var _b;
    const { cachePath, hmrStaticPath } = config_1.config;
    try {
        fs_1.default.rmdirSync(cachePath, { recursive: true });
    }
    catch (e) {
        if (e.code !== 'ENOENT')
            log.error('rm cache dir error');
    }
    if (!config_1.config.isCluster) {
        const { importTunnel } = yield Promise.resolve().then(() => tslib_1.__importStar(require('@/child-process/import-addon')));
        yield importTunnel();
    }
    yield fs_1.default.promises.mkdir(cachePath, { recursive: true });
    yield fs_1.default.promises.mkdir(hmrStaticPath, { recursive: true });
    db_1.initDbModel();
    client_1.initAppClient();
    const { port, iWDPPort, clearAddrInUse } = global.debugAppArgv;
    if (clearAddrInUse) {
        try {
            yield kill_port_1.default(port, 'tcp');
            yield kill_port_1.default(iWDPPort, 'tcp');
        }
        catch (e) {
            log.error('Address %s %s already in use! %s', port, iWDPPort, (_b = e) === null || _b === void 0 ? void 0 : _b.stack);
            return process.exit(1);
        }
    }
});
const showHippyGuide = () => {
    log.info(safe_1.default.bold[enum_1.WinstonColor.Green](`hippy debug steps:
1. start debug server by run 'npm run hippy:debug'
2. start dev server by run 'npm run hippy:dev'
3. open hippy pages with debugMode on mobile/emulator
4. find connected debug targets on devtools home page: ${safe_1.default.underline[enum_1.WinstonColor.Blue](url_1.getHomeUrl())}

find full guide on ${safe_1.default.underline[enum_1.WinstonColor.Blue]('https://hippyjs.org/#/guide/debug')}`));
};
