"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 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 port_1 = require("@/utils/port");
const file_1 = require("@/utils/file");
const log = new log_1.Logger('debug-server', enum_1.WinstonColor.Yellow);
let server;
let socketServer;
/**
 * 开启调试服务
 */
const startDebugServer = async () => {
    log.info('start server argv: %j', global.debugAppArgv);
    await init();
    const { host, port, env } = global.debugAppArgv;
    if (env === "hippy" /* Hippy */)
        showHippyGuide();
    const app = new koa_1.default();
    router_1.routeApp(app);
    server = app.listen(port, host, async () => {
        if (!config_1.config.isCluster) {
            const { startTunnel, startChrome } = await Promise.resolve().then(() => tslib_1.__importStar(require('./child-process/index')));
            await startTunnel();
            startChrome();
            const { startAdbProxy } = await 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 = async (exitProcess = false, ...arg) => {
    var _a;
    try {
        log.info('stopServer %j', arg);
        if (socketServer) {
            await 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;
/**
 * init DB, directory, Tunnel.node, AppClient
 */
const init = async () => {
    normalizeArgv();
    await port_1.checkPort();
    const { cachePath, hmrStaticPath } = config_1.config;
    // clean all unused file
    file_1.rmFolder(cachePath);
    file_1.rmFolder(hmrStaticPath);
    if (!config_1.config.isCluster) {
        const { importTunnel } = await Promise.resolve().then(() => tslib_1.__importStar(require('@/child-process/import-addon')));
        await importTunnel();
    }
    await fs_1.default.promises.mkdir(cachePath, { recursive: true });
    await fs_1.default.promises.mkdir(hmrStaticPath, { recursive: true });
    db_1.initDbModel();
    client_1.initAppClient();
};
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')}`));
};
/**
 * set default tunnel in different framework
 */
const normalizeArgv = () => {
    const { env, tunnel } = global.debugAppArgv;
    if (tunnel)
        return;
    if (["hippy" /* Hippy */, "HippyTDF" /* HippyTDF */].includes(env)) {
        global.debugAppArgv.tunnel = enum_1.DebugTunnel.WS;
    }
    else if (env === "TDFCore" /* TDFCore */) {
        global.debugAppArgv.tunnel = enum_1.DebugTunnel.TCP;
    }
};
