import { system, world } from '@minecraft/server';
import { showMenu } from './ui';


export const dimensions = [world.getDimension('overworld'), world.getDimension('nether'), world.getDimension('the_end')];


world.afterEvents.itemUse.subscribe(({ itemStack, source }) => {
    if (itemStack.typeId == 'monkey:textmenu') showMenu(source);
});



const scoreboard = world.scoreboard;
const f = { 'commands.scoreboard.players.offlinePlayerName': 'Offline Player' };
system.runInterval(() => {
    for (const dimension of dimensions) for (const entity of dimension.getEntities({ type: 'monkey:floatingtext', families: ['scoreboard'] })) {
        const info = JSON.parse(entity.getDynamicProperty('scoreboardinfo') ?? 'null');
        if (!info) { entity.remove(); continue }
        const scoreboardObjective = scoreboard.getObjective(info[0]);
        if (!scoreboardObjective) { entity.remove(); continue };
        const scoreboardScores = scoreboardObjective.getScores().filter(({ participant }) => !participant.displayName.startsWith('#'));
        if (!info[1]) scoreboardScores.sort((a, b) => a.score - b.score);
        else scoreboardScores.sort((a, b) => b.score - a.score);
        entity.nameTag = scoreboardObjective.displayName + '§r\n' + scoreboardScores
            .slice(0, info[6])
            .map(({ participant: { displayName }, score }, i) => `${info[2] ? `${info[3] + (i + 1)}. ` : ''}${info[4] + (f[displayName] ?? displayName)}§r ${info[5] + score}§r`)
            .join('\n');
    }
}, 20);