import { EquipmentSlot, system } from "@minecraft/server";
import { afterEvents, namespace as ns, world } from "./eternal/constants";
import { runInterval } from "./eternal/utils";

const loops = new Map();

afterEvents.itemUse.subscribe(async (e) => {
  const { source: player, itemStack } = e;

  if (itemStack.typeId === `${ns}:drumset`) {
    player.playSound(`${ns}.random.drumset.play`);
    player.runCommand(`event entity @e[r=100] ecbl_bc:event_drum_on`);

    const loop = runInterval(() => {
      if (player.isUsingItem) {
        player.playSound(`${ns}.random.drumset.play`);
        player.runCommand(`event entity @e[r=100] ecbl_bc:event_drum_on`);

      } else loop.dispose();
    }, 80);
    loops.set(player.id, loop);
  }
});

afterEvents.itemStopUse.subscribe((e) => {
  const { source: player, itemStack } = e;

  if (itemStack?.typeId === `${ns}:drumset`) {
    player.stopSound(`${ns}.random.drumset.play`);
    player.runCommand(`event entity @e[r=100] ecbl_bc:event_drum_off`);

    if (loops.has(player.id)) {
      system.clearRun(loops.get(player.id)._process);
      loops.delete(player.id);
    }

    player.damageItem(EquipmentSlot.Mainhand);
  }
});
