/*!
 * Built by Revolist OU ❤️
 */
/**
 * Plugin service
 * Manages plugins
 */
export class PluginService {
    constructor() {
        /**
         * Plugins
         * Define plugins collection
         */
        this.internalPlugins = [];
    }
    /**
     * Get all plugins
     */
    get() {
        return [...this.internalPlugins];
    }
    /**
     * Add plugin to collection
     */
    add(plugin) {
        this.internalPlugins.push(plugin);
    }
    /**
     * Add user plugins and create
     */
    addUserPluginsAndCreate(element, plugins = [], prevPlugins, pluginData) {
        if (!pluginData) {
            return;
        }
        // Step 1: Identify plugins to remove, compare new and old plugins
        const pluginsToRemove = (prevPlugins === null || prevPlugins === void 0 ? void 0 : prevPlugins.filter(prevPlugin => !plugins.some(userPlugin => userPlugin === prevPlugin))) || [];
        // Step 2: Remove old plugins
        pluginsToRemove.forEach(plugin => {
            var _a, _b;
            const index = this.internalPlugins.findIndex(createdPlugin => createdPlugin instanceof plugin);
            if (index !== -1) {
                (_b = (_a = this.internalPlugins[index]).destroy) === null || _b === void 0 ? void 0 : _b.call(_a);
                this.internalPlugins.splice(index, 1); // Remove the plugin
            }
        });
        // Step 3: Register user plugins
        plugins === null || plugins === void 0 ? void 0 : plugins.forEach(userPlugin => {
            // check if plugin already exists, if so, skip
            const existingPlugin = this.internalPlugins.find(createdPlugin => createdPlugin instanceof userPlugin);
            if (existingPlugin) {
                return;
            }
            this.add(new userPlugin(element, pluginData));
        });
    }
    /**
     * Get plugin by class
     */
    getByClass(pluginClass) {
        return this.internalPlugins.find(p => p instanceof pluginClass);
    }
    /**
     * Remove plugin
     */
    remove(plugin) {
        var _a, _b;
        const index = this.internalPlugins.indexOf(plugin);
        if (index > -1) {
            (_b = (_a = this.internalPlugins[index]).destroy) === null || _b === void 0 ? void 0 : _b.call(_a);
            this.internalPlugins.splice(index, 1);
        }
    }
    /**
     * Remove all plugins
     */
    destroy() {
        this.internalPlugins.forEach(p => { var _a; return (_a = p.destroy) === null || _a === void 0 ? void 0 : _a.call(p); });
        this.internalPlugins = [];
    }
}
