import { world } from '@minecraft/server';

const DISC_ID = 'pa:disco_de_musica_primaveral';
const SOUND_ID = 'record.disco_de_musica_primaveral';
const TITLE_MESSAGE = 'actionbar §dNow Playing: Primaveral - Midnight Swell';


const activeJukeboxes = new Map();

world.afterEvents.playerInteractWithBlock.subscribe(event => {
    const { player, itemStack, block } = event;

    if (!block.permutation.matches('minecraft:jukebox')) {
        return;
    }

    const jukeboxId = `${block.location.x},${block.location.y},${block.location.z}`;

    if (itemStack && itemStack.typeId === DISC_ID) {
        player.runCommandAsync(`title @a[r=10] ${TITLE_MESSAGE}`);
        block.dimension.playSound(SOUND_ID, block.location);
        
        activeJukeboxes.set(jukeboxId, true);
    
    } else if (activeJukeboxes.has(jukeboxId)) {
        player.runCommandAsync(`stopsound @a[r=64] ${SOUND_ID}`);
        
        activeJukeboxes.delete(jukeboxId);
    }
});

world.afterEvents.playerBreakBlock.subscribe(event => {
    const { player, brokenBlockPermutation, block } = event;

    if (brokenBlockPermutation.matches('minecraft:jukebox')) {
        const jukeboxId = `${block.location.x},${block.location.y},${block.location.z}`;

        if (activeJukeboxes.has(jukeboxId)) {
            player.runCommandAsync(`stopsound @a[r=64] ${SOUND_ID}`);
            
            activeJukeboxes.delete(jukeboxId);
        }
    }
});