"use strict";

Object.defineProperty(exports, "__esModule", {
    value: !0
}), exports.PluginManager = void 0;

class PluginManager {
    constructor(table, options) {
        var _a;
        this.plugins = new Map, this.pluginEventMap = new Map, this.table = table, null === (_a = options.plugins) || void 0 === _a || _a.map((plugin => {
            this.register(plugin), this._bindTableEventForPlugin(plugin);
        }));
    }
    register(plugin) {
        this.plugins.set(plugin.id, plugin);
    }
    registerAll(plugins) {
        plugins.forEach((plugin => this.register(plugin)));
    }
    getPlugin(id) {
        return this.plugins.get(id);
    }
    getPluginByName(name) {
        return Array.from(this.plugins.values()).find((plugin => plugin.name === name));
    }
    _bindTableEventForPlugin(plugin) {
        var _a;
        null === (_a = plugin.runTime) || void 0 === _a || _a.forEach((runTime => {
            const id = this.table.on(runTime, ((...args) => {
                var _a;
                null === (_a = plugin.run) || void 0 === _a || _a.call(plugin, ...args, runTime, this.table);
            }));
            this.pluginEventMap.set(plugin.id, [ ...this.pluginEventMap.get(plugin.id) || [], id ]);
        }));
    }
    removeOrAddPlugins(plugins) {
        Array.from(this.plugins.values()).filter((plugin => !(null == plugins ? void 0 : plugins.some((p => p.id === plugin.id))))).forEach((plugin => {
            var _a;
            null === (_a = this.pluginEventMap.get(plugin.id)) || void 0 === _a || _a.forEach((id => {
                this.table.off(id);
            })), this.release(), this.plugins.delete(plugin.id);
        }));
        const addedPlugins = null == plugins ? void 0 : plugins.filter((plugin => !this.plugins.has(plugin.id)));
        null == addedPlugins || addedPlugins.forEach((plugin => {
            this.register(plugin), this._bindTableEventForPlugin(plugin);
        }));
    }
    updatePlugins(plugins) {
        null == plugins || plugins.forEach((plugin => {
            plugin.update && plugin.update();
        }));
    }
    release() {
        this.plugins.forEach((plugin => {
            var _a;
            null === (_a = plugin.release) || void 0 === _a || _a.call(plugin, this.table);
        }));
    }
}

exports.PluginManager = PluginManager;
//# sourceMappingURL=plugin-manager.js.map
