import { system, world } from "@minecraft/server";

/**
 * Manager for functions.
 */
export class FunctionManager {
  private constructor() {}
  /**
   * Run function when the player spawn.
   * @param path The function's path.
   * @param initialSpawn If true, the function will only run on player's initial spawn.
   */
  static playerSpawnTrigger(path: string, initialSpawn: boolean = false): void {
    world.afterEvents.playerSpawn.subscribe((event) => {
      if (initialSpawn) {
        if (event.initialSpawn)
          event.player.runCommandAsync(`function ${path}`);
      } else {
        event.player.runCommandAsync(`function ${path}`);
      }
    });
  }
  /**
   * Run function when the player leave.
   * @param path The function's path.
   */
  static playerLeaveTrigger(path: string): void {
    world.beforeEvents.playerLeave.subscribe((event) => {
      event.player.runCommandAsync(`function ${path}`);
    });
  }
  /**
   * Run function when a chat message has been broadcast or sent to players.
   * @param path The function's path.
   * @param msg Message that trigger run funciton
   */
  static chatTrigger(path: string, msg: string): void {
    world.beforeEvents.chatSend.subscribe((event) => {
      if (event.message === msg) {
        event.cancel = true;
        system.runTimeout(() => {
          event.sender.runCommandAsync(`function ${path}`);
        }, 10);
      }
    });
  }
}