"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DevtoolsPlugin = void 0;
const http_1 = __importDefault(require("http"));
const path_1 = __importDefault(require("path"));
const express_1 = __importDefault(require("express"));
const ws_1 = require("ws");
const uuid = __importStar(require("uuid"));
const teams_common_1 = require("@microsoft/teams.common");
const teams_apps_1 = require("@microsoft/teams.apps");
const package_json_1 = __importDefault(require("../package.json"));
const routes_1 = require("./routes");
let DevtoolsPlugin = class DevtoolsPlugin {
    log;
    id;
    name;
    httpPlugin;
    $onError;
    $onActivity;
    http;
    express;
    ws;
    sockets = new Map();
    pending = {};
    pages = [];
    constructor() {
        const dist = path_1.default.join(__dirname, 'devtools-web');
        this.express = (0, express_1.default)();
        this.http = http_1.default.createServer(this.express);
        this.ws = new ws_1.WebSocketServer({ server: this.http, path: '/devtools/sockets' });
        this.ws.on('connection', this.onSocketConnection.bind(this));
        this.express.use('/devtools', express_1.default.static(dist));
        this.express.get('/devtools/*', (_, res) => {
            res.sendFile(path_1.default.join(dist, 'index.html'));
        });
    }
    /**
     * add a custom page to the devtools
     * @param page the page to add
     */
    addPage(page) {
        this.pages.push(page);
        return this;
    }
    onInit() {
        this.log.warn(new teams_common_1.String()
            .bold(new teams_common_1.String().yellow(`⚠️  Devtools are not secure and should not be used production environments ⚠️`))
            .toString());
    }
    onStart({ port }) {
        port += 1;
        this.express.use((0, routes_1.router)({
            port,
            log: this.log,
            process: (token, activity) => {
                return new Promise((resolve, reject) => {
                    this.pending[activity.id] = { resolve, reject };
                    this.$onActivity({
                        sender: this.httpPlugin,
                        token,
                        activity,
                    });
                });
            },
        }));
        return new Promise((resolve, reject) => {
            this.http.on('error', (error) => {
                this.$onError({ error });
                return reject(error);
            });
            this.http.listen(port, async () => {
                this.log.info(`available at http://localhost:${port}/devtools`);
                resolve();
            });
        });
    }
    onActivity({ activity, conversation }) {
        this.emitActivityToSockets({
            id: uuid.v4(),
            type: 'activity.received',
            chat: conversation,
            body: activity,
            sentAt: new Date(),
        });
    }
    onActivitySent({ activity, conversation }) {
        this.emitActivityToSockets({
            id: uuid.v4(),
            type: 'activity.sent',
            chat: conversation,
            body: activity,
            sentAt: new Date(),
        });
    }
    onActivityResponse({ activity, response }) {
        const promise = this.pending[activity.id];
        if (!promise)
            return;
        promise.resolve(response);
        delete this.pending[activity.id];
    }
    async send(activity, ref) {
        return await this.httpPlugin.send(activity, ref);
    }
    createStream(ref) {
        return this.httpPlugin.createStream(ref);
    }
    onSocketConnection(socket) {
        const id = uuid.v4();
        this.sockets.set(id, socket);
        socket.send(JSON.stringify({
            id: uuid.v4(),
            type: 'metadata',
            body: {
                id: this.id?.toString(),
                name: this.name?.toString(),
                pages: this.pages,
            },
            sentAt: new Date(),
        }));
        socket.on('disconnect', () => {
            this.sockets.delete(id);
        });
    }
    emitToSockets(event) {
        for (const socket of this.sockets.values()) {
            socket.send(JSON.stringify(event));
        }
    }
    emitActivityToSockets(event) {
        for (const socket of this.sockets.values()) {
            socket.send(JSON.stringify(event));
        }
    }
};
exports.DevtoolsPlugin = DevtoolsPlugin;
__decorate([
    (0, teams_apps_1.Logger)(),
    __metadata("design:type", Object)
], DevtoolsPlugin.prototype, "log", void 0);
__decorate([
    (0, teams_apps_1.Dependency)({ optional: true }),
    __metadata("design:type", Object)
], DevtoolsPlugin.prototype, "id", void 0);
__decorate([
    (0, teams_apps_1.Dependency)({ optional: true }),
    __metadata("design:type", Object)
], DevtoolsPlugin.prototype, "name", void 0);
__decorate([
    (0, teams_apps_1.Dependency)(),
    __metadata("design:type", teams_apps_1.HttpPlugin)
], DevtoolsPlugin.prototype, "httpPlugin", void 0);
__decorate([
    (0, teams_apps_1.Event)('error'),
    __metadata("design:type", Function)
], DevtoolsPlugin.prototype, "$onError", void 0);
__decorate([
    (0, teams_apps_1.Event)('activity'),
    __metadata("design:type", Function)
], DevtoolsPlugin.prototype, "$onActivity", void 0);
exports.DevtoolsPlugin = DevtoolsPlugin = __decorate([
    (0, teams_apps_1.Plugin)({
        name: 'devtools',
        version: package_json_1.default.version,
        description: ['a set of tools to make development', 'of teams apps faster and simpler'].join('\n'),
    }),
    __metadata("design:paramtypes", [])
], DevtoolsPlugin);
//# sourceMappingURL=data:application/json;base64, 