import { Entity, GameMode, Player, world } from "@minecraft/server";

world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:briar_place', {
        onPlace: e => {
            const block = e.block

            switch (block.typeId) {
                case "bumble:briar_bush":
                    if (block.above(1).isAir) {
                        block.above(1).setType("bumble:briar_bush_top")
                        block.above(1).setPermutation(block.above(1).permutation.withState('minecraft:cardinal_direction', block.permutation.getState('minecraft:cardinal_direction')))
                    }
                    break;
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:briar_grow', {
        onRandomTick: e => {
            const block = e.block
            let num = Math.round(Math.random() * 8)
            if (num <= 1) {
                block.setType("bumble:briar_bush")
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:briar_shearable', {
        onPlayerInteract: e => {
            const block = e.block
            const item = e.player.getComponent('equippable').getEquipment('Mainhand')
            const player = e.player

            if (item?.typeId == "minecraft:shears") {
                player.runCommandAsync('loot spawn ' + JSON.stringify(block.location.x) + ' ' + JSON.stringify(block.location.y + 1) + ' ' + JSON.stringify(block.location.z) + ' loot "plants/plant_briar_bush_clipped"')
                block.setType("bumble:briar_bush_clipped")
            }
        },
    });
    initEvent.blockComponentRegistry.registerCustomComponent('bumble:briar_damage', {
        onTick: e => {
            const block = e.block
            var entity = block.dimension.getEntitiesAtBlockLocation(block.center())
            if (entity.length > 0) {
                for (let i = 0; i < entity.length; i++) {
                    entity[i].runCommandAsync('effect @s slowness 1 5 true')
                    entity[i].runCommandAsync('effect @s poison 1 2 true')
                }
            }
        },
    });
});
