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

let debug = true; // Ative ou desative o debug aqui

mc.world.afterEvents.playerSpawn.subscribe(data => {
    const player = data.player;
    if (!data.initialSpawn) return;

    const commands = player.getDynamicProperty("ld_eb:init_functions");
    if (!commands) return;

    //if (debug) console1-console.warn(`[DEBUG] Executando comandos para ${player.name}: ${commands}`);

    commands.split("; ").forEach(cmd => {
        if (cmd) {
            //if (debug) console1-console.warn(`[DEBUG] Executando: ${cmd}`);
            player.runCommand(cmd);
        }
    });

    player.setDynamicProperty("ld_eb:init_functions", "");
});

mc.Player.prototype.ld_eb_init_function = function(cmd) {
    if (!cmd) return this.getDynamicProperty("ld_eb:init_functions") ?? "";

    const current = (this.getDynamicProperty("ld_eb:init_functions") ?? "").trim();
    const updated = current ? current + "; " + cmd : cmd;

    this.setDynamicProperty("ld_eb:init_functions", updated);

    //if (debug) console1-console.warn(`[DEBUG] Adicionado comando '${cmd}' para ${this.name}`);
};

mc.Player.prototype.ld_eb_remove_function = function(cmd) {
    let commands = this.getDynamicProperty("ld_eb:init_functions") ?? "";
    if (!commands.includes(cmd)) {
        //if (debug) console1-console.warn(`[DEBUG] Comando '${cmd}' não encontrado para ${this.name}`);
        return;
    }

    // Remove espaços extras e divide corretamente
    const updatedCommands = commands.split("; ").map(c => c.trim()).filter(c => c !== cmd).join("; ");

    // Atualiza a DynamicProperty, removendo espaços desnecessários
    this.setDynamicProperty("ld_eb:init_functions", updatedCommands.trim());

    //if (debug) console1-console.warn(`[DEBUG] Comando removido '${cmd}' para ${this.name}`);
};
