import { EquipmentSlot, world, system } from "@minecraft/server";
import { getPlayerEquipment } from "./utils/inventory.js";

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const equipment = getPlayerEquipment(player);
        const helmet = equipment.getEquipment(EquipmentSlot.Head)?.typeId || "none";

        let block = undefined;
        try { block = player.dimension.getBlock(player.getHeadLocation()); } catch {}
        if (!block || !block.isValid()) continue;

        const isWater = block.typeId.includes("water") && block.isLiquid;
        if (!block.isAir && !isWater && block.typeId !== "gs_cb:dynamic_light") continue;

        if (helmet === "gs_cb:miner_helmet") {
            const state = block.permutation.getState("gs_cb:reset");
            const nextState = state === 0 ? 1 : 0;
            block.setType("gs_cb:dynamic_light");
            block.setPermutation(block.permutation.withState("gs_cb:reset", nextState));    
        }
    }

    const entities = world.getDimension("overworld").getEntities();
    const lightEntities = entities.filter(entity =>
        ["gs_cb:orelin", "gs_cb:orelin_lava", "gs_cb:orelin_ice", "gs_cb:orelin_mushroom", "gs_cb:magma_wither"]
            .includes(entity.typeId)
    );
    
    for (const lightEntity of lightEntities) {
        let headLocation = lightEntity.getHeadLocation();
        
        let block = undefined;
        try { block = lightEntity.dimension.getBlock(headLocation); } catch {}
        if (!block || !block.isValid()) continue;

        const isWater = block.typeId.includes("water") && block.isLiquid;
        if (!block.isAir && !isWater && block.typeId !== "gs_cb:dynamic_light") continue;
        
        const state = block.permutation.getState("gs_cb:reset");
        const nextState = state === 0 ? 1 : 0;
        block.setType("gs_cb:dynamic_light");
        block.setPermutation(block.permutation.withState("gs_cb:reset", nextState));
    }
}, 2);