import { system, world } from "@minecraft/server";
import * as utils from "./utils"
import * as gld from "./gld"
import { onTick } from "./battery";

const playerBiome = {};

export async function onTick() {
    for (const player of world.getAllPlayers()) {
        try {
            const targetLocation = player.location;
            targetLocation.y += 2;

            // Check biome
            const biomeCheck = player.dimension.spawnEntity("goe_spa:biome_check", targetLocation);

            // Check weather
            targetLocation.y = player.dimension.heightRange.max;
            const weatherCheck = player.dimension.spawnEntity("goe_spa:biome_check", targetLocation);

                system.runTimeout(() => {
                    if (biomeCheck === undefined || !biomeCheck.isValid())
                        return;
                    const biomeTags = biomeCheck.getTags();
                    const weather = weatherCheck.getProperty("goe_spa:weather");
                    const underground = biomeCheck.getProperty("goe_spa:underground");
                    const in_water = biomeCheck.getProperty("goe_spa:in_water");
                    playerBiome[player.id] = { 
                        player: player, 
                        biomes: biomeTags, 
                        weather: weather, 
                        underground: underground, 
                        in_water: in_water 
                    };

                    biomeCheck.remove();
                    weatherCheck.remove();
                }, 1);
        } catch (error) {}
    }       
}

export function getBiome(player) {
    if (playerBiome[player.id] === undefined)
        return undefined;

    return playerBiome[player.id].biomes[0];
}

export function isInBiome(player, tag) {
    if (playerBiome[player.id] === undefined)
        return false;

    return playerBiome[player.id].biomes.includes(tag);
}

export function getWeather(player) {
    if (playerBiome[player.id] === undefined)
        return 0;

    return playerBiome[player.id].weather;
}

export function isUnderground(player) {
    if (playerBiome[player.id] === undefined)
        return false;

    return playerBiome[player.id].underground;
}

export function isInWater(player) {
    if (playerBiome[player.id] === undefined)
        return false;

    return playerBiome[player.id].in_water;
}