import type { Context } from "../context";
import type { Plugin } from "../plugins/type";

export class PluginManager {
  private context: Context;

  private plugins: Plugin[] = [];

  constructor(context: Context) {
    this.context = context;
    const pluginFactoryList = this.context.config?.plugins || [];
    this.plugins = pluginFactoryList.map(pluginFactory => {
      if ("plugin" in pluginFactory) {
        const { plugin, config } = pluginFactory;
        return plugin(config);
      } else {
        return pluginFactory({});
      }
    });
  }

  registerPlugin = (plugin: Plugin) => {
    this.plugins.push(plugin);
  };

  unregisterPlugin = (plugin: Plugin) => {
    this.plugins = this.plugins.filter(p => p !== plugin);
  };

  unregisterAllPlugin = () => {
    this.plugins = [];
  };

  callPlugin = <K extends keyof Plugin>(
    callbackKey: K,
    data?: Parameters<Required<Plugin>[K]>[1]
  ) => {
    this.plugins.forEach(plugin => {
      const callback = plugin[callbackKey];
      if (typeof callback === "function") {
        callback(this.context, data as any);
      }
    });
  };
}
