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((e) => {
  const { source: player, itemStack } = e;

  if (itemStack.typeId === `${ns}:pan_flute`) {
    player.playSound(`${ns}.random.pan_flute.play`);
    player.runCommand(`event entity @e[r=100] ecbl_bc:event_flute_on`);
    const loop = runInterval(() => {
      if (player.isUsingItem) {
        player.playSound(`${ns}.random.pan_flute.play`);
        player.runCommand(`event entity @e[r=100] ecbl_bc:event_flute_on`);
      } else loop.dispose();
    }, 100);
    loops.set(player.id, loop);
  }
});

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

  if (itemStack?.typeId === `${ns}:pan_flute`) {
    player.stopSound(`${ns}.random.pan_flute.play`);
    player.runCommand(`event entity @e[r=100] ecbl_bc:event_flute_off`);
    if (loops.has(player.id)) {
      system.clearRun(loops.get(player.id)._process);
      loops.delete(player.id);
    }

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

