"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.onVueClientConnection = void 0;
const enum_tdf_mapping_1 = require("tdf-devtools-protocol/dist/types/enum-tdf-mapping");
const enum_1 = require("@/@types/enum");
const log_1 = require("@/utils/log");
const pub_sub_channel_1 = require("@/utils/pub-sub-channel");
const db_1 = require("@/db");
const aegis_1 = require("@/utils/aegis");
const reload_adapter_1 = require("@/utils/reload-adapter");
const debug_targets_1 = require("@/controller/debug-targets");
const log = new log_1.Logger('vue-devtools', enum_1.WinstonColor.Yellow);
const onVueClientConnection = async (ws, wsUrlParams) => {
    const { contextName, clientRole, clientId } = wsUrlParams;
    log.verbose('%s connected, clientId: %s', clientRole, clientId);
    const { Subscriber, Publisher } = db_1.getDBOperator();
    aegis_1.aegis.reportEvent({
        name: enum_1.ReportEvent.VueDevtools,
        ext1: clientId,
        ext2: contextName,
    });
    let internalHandler;
    let internalSubscriber;
    if (clientRole === enum_1.ClientRole.JSRuntime) {
        const internalChannelId = pub_sub_channel_1.createInternalChannel(clientId, '');
        internalSubscriber = new Subscriber(internalChannelId);
        internalHandler = (msg) => {
            if (msg === enum_1.InternalChannelEvent.DevtoolsConnected) {
                // pub enable after devtools connected
                pubEnableVueDevtools();
            }
        };
        internalSubscriber.subscribe(internalHandler);
        // pub enable immediately, support for reload instance
        pubEnableVueDevtools();
        async function pubEnableVueDevtools() {
            const debugTarget = await debug_targets_1.DebugTargetManager.findDebugTarget(clientId, undefined, true);
            reload_adapter_1.publishRes(clientId, {
                method: enum_tdf_mapping_1.TdfEvent.TDFRuntimeEnableVueDevtools,
                params: {
                    contextName: debugTarget === null || debugTarget === void 0 ? void 0 : debugTarget.title,
                },
            });
        }
    }
    const channel = pub_sub_channel_1.createVueDevtoolsChannel(clientId);
    const publisher = new Publisher(channel);
    const subscriber = new Subscriber(channel);
    const handler = (msg) => {
        log.debug('receive %s message: %s', clientRole, msg);
        ws.send(msg.toString());
    };
    subscriber.subscribe(handler);
    if (clientRole === enum_1.ClientRole.JSRuntime)
        publisher.publish(JSON.stringify(["vue-devtools-disconnect-backend" /* BackendDisconnect */]));
    ws.on('message', async (msg) => {
        const msgStr = msg.toString();
        if (msgStr)
            publisher.publish(msgStr);
    });
    ws.on('close', (code, reason) => {
        log.warn('%s ws closed, code: %s, reason: %s', clientRole, code, reason);
        subscriber.unsubscribe(handler);
        subscriber.disconnect();
        if (reason.indexOf('client') !== -1) {
            publisher.publish(JSON.stringify(["vue-devtools-disconnect-devtools" /* DevtoolsDisconnect */]));
        }
        if (clientRole === enum_1.ClientRole.JSRuntime) {
            internalSubscriber.unsubscribe(internalHandler);
            internalSubscriber.disconnect();
        }
    });
    ws.on('error', (e) => log.error('JSRuntime ws error: %s', e.stack || e));
};
exports.onVueClientConnection = onVueClientConnection;
