import { customElement } from "lit/decorators.js";
import { PluginBusyList } from "./plugin-busy-list/component";

export interface PluginTask {
  taskId: string;
  taskDescription: string;
}

/**
 * @deprecated Use the `canDispose(api)` plugin lifecycle hook instead. Plugins should
 * decide whether they can be disposed (e.g. show their own confirmation modal) rather
 * than relying on shell-level busy tasks. This API is kept for backwards compatibility.
 */
export abstract class PluginBusyManager {
  abstract addTask(task: PluginTask): void;
  abstract removeTask(taskId: string): void;
  abstract clearAll(): void;
  abstract isBusy(): boolean;
  abstract getTasks(): PluginTask[];
}

/** @deprecated See {@link PluginBusyManager}. */
export class PluginBusyManagerImpl implements PluginBusyManager {
  private tasks: PluginTask[] = [];

  constructor() {
    if (!customElements.get("plugin-busy-list")) {
      customElement("plugin-busy-list")(PluginBusyList);
    }
  }

  public addTask(task: PluginTask): void {
    const exists = this.tasks.some((t) => t.taskId === task.taskId);
    if (!exists) {
      this.tasks.push(task);
    }
  }

  public removeTask(taskId: string): void {
    const index = this.tasks.findIndex((item) => item.taskId === taskId);
    if (index > -1) {
      this.tasks.splice(index, 1);
    }
  }

  public isBusy(): boolean {
    return this.tasks.length > 0;
  }

  public clearAll(): void {
    this.tasks = [];
  }

  public getTasks(): PluginTask[] {
    return this.tasks;
  }
}
