import { Entity, MinecraftDimensionTypes, system, world } from "@minecraft/server";
import { Fogs } from "../data/fogs";
import { isDayTime, isUnderground } from "../utils/utils";
import { getPlayerConfigurations } from "./entities_controller";

world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
    const { entity, eventId } = event;

    if (entity.typeId == "ns_rh:biome_detector2") {
        if (eventId.startsWith("biome_tag")) {
            const biomeTag = eventId;

            //APPLY FOG
            const fog = Fogs.get(biomeTag) ?? Fogs.get("biome_tag:default");

            if (!entity) return;

            const dimension = entity?.dimension;

            if (!dimension) return;

            const dimensionId = entity?.dimension?.id;

            system.runTimeout(() => {
                //  console.warn(dimensionId);

                if (entity && dimensionId && dimensionId == MinecraftDimensionTypes.overworld) {
                    try {
                        const ownerId = entity?.getDynamicProperty("owner") ?? "none";

                        const owner = world.getAllPlayers().find((p) => p.id == ownerId);

                        owner.setDynamicProperty("in_biome", biomeTag);

                        if (owner) {
                            const playerConfigurations = getPlayerConfigurations(owner);

                            if (playerConfigurations.enable_fog) {
                                if (fog) {
                                    owner.runCommand("fog @s pop ns_rh_fog");
                                    owner.runCommand(`fog @s push ${getFog(owner, fog)} ns_rh_fog`);
                                } else {
                                    owner.runCommand("fog @s remove ns_rh_fog");
                                }
                            } else {
                                owner.runCommand("fog @s remove ns_rh_fog");
                            }
                        }
                    } catch (error) {}
                }
            }, 0);

            //...
        }
    }
});

/**
 *
 * @param {Entity} entity
 * @param {{fogs:object}} fog
 * @returns {string}
 */
function getFog(entity, fog) {
    if (isUnderground(entity)) {
        return Fogs.get("biome_tag:default").fogs.underground;
    } else {
        return isDayTime() ? fog.fogs.day_time : fog.fogs.night_time;
    }
}
