import * as mc from "@minecraft/server";

// play start sound, after 1.75 seconds start playing the loop
export function start(entity) {
  const players = getPlayers(entity);
  for (let player of players) {
    if (!player.isValid()) continue;
    player.runCommand("/playsound hf_mzs:music.sculptor.start @s ~ ~ ~ 0.5 1 0.5");
  }
}
export function startLoop(entity) {
  mc.system.runTimeout(() => {
    const players = getPlayers(entity);
    for (let player of players) {
      player.runCommand("/stopsound @s hf_mzs:music.sculptor.start");
      loopMusic(player);
    }
  }, 2);
}

function loopMusic(entity) {
  if (!entity.isValid()) return;
  entity.runCommand("/stopsound @s hf_mzs:music.sculptor.music");
  entity.runCommand("/playsound hf_mzs:music.sculptor.music @s ~ ~ ~ 0.5 1 0.5");
  mc.system.runTimeout(() => {
    if (entity.hasTag("hf_mzs_sculptor_test")) loopMusic(entity);
  }, 128 * 20);
}

export function end(entity, success) {
  entity.runCommand("/stopsound @a[r=64] hf_mzs:music.sculptor.music");
  const players = getPlayers(entity);
  for (let player of players) {
    if (!player.isValid()) continue;
    if (success) player.runCommand("/playsound hf_mzs:music.sculptor.outro @s ~ ~ ~ 0.5 1 0.5");
    entity.setDynamicProperty("hf_mzs:playing_outro", true);
  }
}

function getPlayers(entity) {
  return entity.dimension.getEntities({
    maxDistance: 64,
    families: ["player"],
    location: entity.location,
  });
}
