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

let isFullMoonExecuted = false;  // Variable global para controlar la ejecución

export function moontest() {
    const fullMoonTag = "fullmoon";
    const overworld = world.getDimension("overworld");

    // Get the current time of day (0 to 23999)
    const time = world.getTimeOfDay();

    // Detect if it's the full moon (around 18000 ticks)
    if (time >= 17900 && time <= 18100 && !isFullMoonExecuted) { 
        // Full moon logic (allowing for a slight margin of error around 18000 ticks)
        // Add full moon tag to all players
        for (const player of world.getPlayers()) {
            if (!player.hasTag(fullMoonTag)) {
                player.addTag(fullMoonTag);  // Add the full moon tag to players
            }
        }
        // Execute function fm_rise for the world (not for individual players)
        overworld.runCommandAsync('function fm_rise').catch(err => console.error("Error executing fm_rise:", err));
        isFullMoonExecuted = true;  // Set to true so it doesn't execute again until reset
    } 
    // Detect when it's no longer the full moon (morning)
    else if ((time < 17900 || time > 18100) && isFullMoonExecuted) {
        // Remove full moon tag from all players
        for (const player of world.getPlayers()) {
            if (player.hasTag(fullMoonTag)) {
                player.removeTag(fullMoonTag);  // Remove the full moon tag from players
            }
        }
        // Execute function fm_fade for the world (not for individual players)
        overworld.runCommandAsync('function fm_fade').catch(err => console.error("Error executing fm_fade:", err));
        isFullMoonExecuted = false;  // Reset so it can execute again next night
    }
}
