import { world, system } from "@minecraft/server";
import * as utils from "./utils";
import * as Vector3 from "./vector3";

export async function onTick() {
    handlePlayers();
    handleMobs();
}

async function handlePlayers() {
    for (const player of world.getAllPlayers()) {
        let block = player.dimension.getBlock(player.location);
        if (block === undefined)
            continue;
        
        if (block.typeId !== "goe_bos:spider_web" && block.typeId !== "goe_bos:purple_web")
        {
            block = player.dimension.getBlock({ x: player.location.x, y: player.location.y + 1, z: player.location.z});
            if (block === undefined || block.typeId !== "goe_bos:spider_web" || block.typeId !== "goe_bos:purple_web")
                continue;
        }

        const playerVelocity = player.getVelocity();
        const slownessVeloctiy = new Vector3.Vector3(playerVelocity).multiply(-1);

        const slownessHorizontalSpeed = Vector3.length({ x: slownessVeloctiy.x, y: 0, z: slownessVeloctiy.z });
        const slownessVerticalSpeed = slownessVeloctiy.y * 0.1;

        player.applyKnockback(slownessVeloctiy.x, slownessVeloctiy.z, slownessHorizontalSpeed, slownessVerticalSpeed);

        // player.addEffect("slowness", 5, { amplifier: 2, showParticles: false });
    }
}

async function handleMobs() {
    const entities = utils.overworld.getEntities().concat(utils.the_end.getEntities().concat(utils.nether.getEntities()));

    for (const entity of entities) {
        try {
            if (entity.typeId === "minecraft:player") continue;

            let block = entity.dimension.getBlock(entity.location);
            if (block === undefined)
                continue;
            
            if (block.typeId !== "goe_bos:purple_web")
            {
                block = entity.dimension.getBlock({ x: entity.location.x, y: entity.location.y + 1, z: entity.location.z});
                if (block === undefined || block.typeId !== "goe_bos:purple_web")
                    continue;
            }

            entity.addEffect("slowness", 5, { amplifier: 2, showParticles: false });
        } catch (error) {
            
        }
    }
}

export async function onPlayerBreakBlock(event) {
    const block = event.block;
    const targetLocation = block.location;
    targetLocation.x += 0.5;
    targetLocation.y += 0.3;
    targetLocation.z += 0.5;
    block.dimension.spawnParticle("goe_bos:skeleton_death", targetLocation);

    const player = event.player;
    utils.runPlayerCommand(player, "playsound goe_bos:web_destroy @a[r=10]");
}