import type { BootstrappedPlugin, PluginDefinition, Plugin as PluginType } from "@uxland/harmonix";
import { bootstrapPlugins as pluginBootstrapper } from "@uxland/harmonix";
import {
  dispose as activityHistoryDispose,
  initialize as activityHistoryInitialize,
} from "../../../plugins/activity-history/src/plugin";
import { PrimariaApi, primariaApiFactory } from "./api/api";
export type { PluginDefinition, PluginInfo } from "@uxland/harmonix";

let bootstrappedPlugins = [] as BootstrappedPlugin<PrimariaApi>[];

export interface PrimariaPlugin extends Plugin {
  startup: (api: PrimariaApi, startupParams: any) => Promise<void>;
}

export interface PrimariaStartupPlugin {
  pluginId: string;
  params: any;
}

interface PrimariaBootstrappedPlugin extends BootstrappedPlugin<PrimariaApi> {
  importedPlugin: PrimariaPlugin;
}

const internalPlugins: PluginDefinition[] = [
  {
    pluginId: "activity-history",
    importer: () =>
      Promise.resolve({
        initialize: activityHistoryInitialize,
        dispose: activityHistoryDispose,
      }),
  },
];

export const bootstrapPlugins = async (plugins: PluginDefinition[], startup?: PrimariaStartupPlugin) => {
  const finalPlugins = internalPlugins.concat(plugins || []);
  bootstrappedPlugins = (await pluginBootstrapper(finalPlugins, primariaApiFactory)) as BootstrappedPlugin<PrimariaApi>[];
  handleStartupPlugin(bootstrappedPlugins as PrimariaBootstrappedPlugin[], startup);
};

export const handleStartupPlugin = (plugins: PrimariaBootstrappedPlugin[], startupPlugin?: PrimariaStartupPlugin) => {
  if (plugins && plugins.length > 0 && startupPlugin?.pluginId) {
    const plugin = plugins.find(
      (plugin: PrimariaBootstrappedPlugin) => plugin?.apiInstance.pluginInfo.pluginId === startupPlugin.pluginId,
    );
    if (plugin?.importedPlugin?.startup) plugin?.importedPlugin?.startup?.(plugin.apiInstance, startupPlugin.params);
  }
};

export const disposePlugins = async () => {
  return Promise.all(bootstrappedPlugins.map((plugin: PrimariaBootstrappedPlugin) => plugin?.dispose()));
};

export type Plugin = PluginType<PrimariaApi>;
