import { BROKER_EVENTS } from "../broker/broker-events";
import { PrimariaBroker } from "../broker/primaria-broker";

export interface QuickActionTask {
  taskId: string;
}

export abstract class QuickActionBusyManager {
  abstract addTask(task: QuickActionTask): void;
  abstract removeTask(taskId: string): void;
  abstract clearAll(): void;
  abstract isBusy(): boolean;
}

export class QuickActionBusyManagerImpl implements QuickActionBusyManager {
  private tasks: QuickActionTask[] = [];

  constructor(private broker: PrimariaBroker) {}

  public addTask(task: QuickActionTask): void {
    const index = this.tasks.findIndex((item) => item.taskId === task.taskId);
    if (index > -1) {
      return;
    }

    this.tasks.push(task);
    this.emitBusyChanged();
  }

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

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

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

  private emitBusyChanged(): void {
    const busy = this.isBusy();
    this.broker.publish(BROKER_EVENTS.shell.quickActionBusyChanged, { busy });
  }
}
