import { system, world, Player } from "@minecraft/server";

Player.prototype.isMusicPlaying = false;
Player.prototype.musicTime = 0;

const MUSIC_HANDLER = system.runInterval(() => {
    const players = world.getAllPlayers();

    for (let player of players) {
        const nearbyClown = player.dimension.getEntities({
            location: player.location,
            families: ["clown"],
            maxDistance: 64,
            closest: 1,
        });

        if (nearbyClown.length > 0) {
            const clown = nearbyClown[0];

            if (clown.matches({ excludeTypes: ["px_hc:jester_clone"] })) {
                if (player.isMusicPlaying == false) {
                    player.isMusicPlaying = true;
                    player.playMusic("circus.theme", { loop: true });
                }
            }
        } else {
            if (player.isMusicPlaying == true) {
                player.isMusicPlaying = false;
                player.musicTime = 0;
                player.stopMusic();
            }
        }
    }
}, 1 * 20);
