"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const node_vm_1 = require("node:vm");
const bind_decorator_1 = __importDefault(require("bind-decorator"));
const json_stable_stringify_without_jsonify_1 = __importDefault(require("json-stable-stringify-without-jsonify"));
const data_1 = __importDefault(require("../util/data"));
const logger_1 = __importDefault(require("../util/logger"));
const settings = __importStar(require("../util/settings"));
const utils_1 = __importDefault(require("../util/utils"));
const extension_1 = __importDefault(require("./extension"));
const SUPPORTED_OPERATIONS = ['save', 'remove'];
class ExternalJSExtension extends extension_1.default {
    mqttTopic;
    requestRegex;
    basePath;
    constructor(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension, mqttTopic, folderName) {
        super(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension);
        this.mqttTopic = mqttTopic;
        this.requestRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/request/${mqttTopic}/(save|remove)`);
        this.basePath = data_1.default.joinPath(folderName);
    }
    async start() {
        await super.start();
        this.eventBus.onMQTTMessage(this, this.onMQTTMessage);
        await this.loadFiles();
        await this.publishExternalJS();
    }
    getFilePath(name, mkBasePath = false) {
        if (mkBasePath && !node_fs_1.default.existsSync(this.basePath)) {
            node_fs_1.default.mkdirSync(this.basePath, { recursive: true });
        }
        return node_path_1.default.join(this.basePath, name);
    }
    getFileCode(name) {
        return node_fs_1.default.readFileSync(node_path_1.default.join(this.basePath, name), 'utf8');
    }
    *getFiles() {
        if (!node_fs_1.default.existsSync(this.basePath)) {
            return;
        }
        for (const fileName of node_fs_1.default.readdirSync(this.basePath)) {
            if (fileName.endsWith('.js')) {
                yield { name: fileName, code: this.getFileCode(fileName) };
            }
        }
    }
    async onMQTTMessage(data) {
        const match = data.topic.match(this.requestRegex);
        if (match && SUPPORTED_OPERATIONS.includes(match[1].toLowerCase())) {
            const message = utils_1.default.parseJSON(data.message, data.message);
            try {
                let response;
                if (match[1].toLowerCase() === 'save') {
                    response = await this.save(message);
                }
                else {
                    response = await this.remove(message);
                }
                await this.mqtt.publish(`bridge/response/${this.mqttTopic}/${match[1]}`, (0, json_stable_stringify_without_jsonify_1.default)(response));
            }
            catch (error) {
                logger_1.default.error(`Request '${data.topic}' failed with error: '${error.message}'`);
                const response = utils_1.default.getResponse(message, {}, `${error.message}`);
                await this.mqtt.publish(`bridge/response/${this.mqttTopic}/${match[1]}`, (0, json_stable_stringify_without_jsonify_1.default)(response));
            }
        }
    }
    async remove(message) {
        if (!message.name) {
            return utils_1.default.getResponse(message, {}, `Invalid payload`);
        }
        const { name } = message;
        const toBeRemoved = this.getFilePath(name);
        if (node_fs_1.default.existsSync(toBeRemoved)) {
            await this.removeJS(name, this.loadModuleFromText(this.getFileCode(name), name));
            node_fs_1.default.rmSync(toBeRemoved, { force: true });
            logger_1.default.info(`${name} (${toBeRemoved}) removed.`);
            await this.publishExternalJS();
            return utils_1.default.getResponse(message, {});
        }
        else {
            return utils_1.default.getResponse(message, {}, `${name} (${toBeRemoved}) doesn't exists`);
        }
    }
    async save(message) {
        if (!message.name || !message.code) {
            return utils_1.default.getResponse(message, {}, `Invalid payload`);
        }
        const { name, code } = message;
        try {
            await this.loadJS(name, this.loadModuleFromText(code, name));
            const filePath = this.getFilePath(name, true);
            node_fs_1.default.writeFileSync(filePath, code, 'utf8');
            logger_1.default.info(`${name} loaded. Contents written to '${filePath}'.`);
            await this.publishExternalJS();
            return utils_1.default.getResponse(message, {});
        }
        catch (error) {
            return utils_1.default.getResponse(message, {}, `${name} contains invalid code: ${error.message}`);
        }
    }
    async loadFiles() {
        for (const extension of this.getFiles()) {
            await this.loadJS(extension.name, this.loadModuleFromText(extension.code, extension.name));
        }
    }
    async publishExternalJS() {
        await this.mqtt.publish(`bridge/${this.mqttTopic}s`, (0, json_stable_stringify_without_jsonify_1.default)(Array.from(this.getFiles())), {
            retain: true,
            qos: 0,
        }, settings.get().mqtt.base_topic, true);
    }
    loadModuleFromText(moduleCode, name) {
        const moduleFakePath = node_path_1.default.join(__dirname, '..', '..', 'data', 'extension', name);
        const sandbox = {
            require: require,
            module: {},
            console,
            setTimeout,
            clearTimeout,
            setInterval,
            clearInterval,
            setImmediate,
            clearImmediate,
        };
        (0, node_vm_1.runInNewContext)(moduleCode, sandbox, moduleFakePath);
        return sandbox.module.exports;
    }
}
exports.default = ExternalJSExtension;
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "onMQTTMessage", null);
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "remove", null);
__decorate([
    bind_decorator_1.default
], ExternalJSExtension.prototype, "save", null);
//# sourceMappingURL=data:application/json;base64, 