import { projectileManager } from "../projectilesManager";
import { SuppEntities } from "../reg/suppEntities";
import { Direction, system, world } from "@minecraft/server";
import { SuppItems } from "../reg/suppItems";
import { lengthSquared, random } from "../util/mthUtils";
import { breakBlock, getBlocksInRadius, shrinkIfInSurvival } from "../util/miscUtils";
import { breakWhenPushed, isFluid, isGlass } from "../util/blockProperties";
import { SuppTags } from "../reg/suppTags";
import { McParticles } from "../reg/mcParticles";
import { offsetVec } from "../util/dirUtils";
projectileManager.registerProjectile(SuppEntities.BombProjectile, {
    onTick(entity, prevPos) {
        const vel = projectileManager.getProjectileVelocity(entity);
        if (lengthSquared(vel) > 0.1) {
            entity.dimension.spawnParticle(McParticles.Smoke, offsetVec(prevPos, Direction.Up, 0.25));
        }
    }
});
world.afterEvents.itemCompleteUse.subscribe((event => {
    const itemStack = event.itemStack;
    if (itemStack.typeId == SuppItems.Bomb) {
        const player = event.source;
        const bomb = projectileManager.shootProjectileFromEntity(player, 1, SuppEntities.BombProjectile, SuppItems.Bomb);
        const pitch = random(0.3, 0.5);
        bomb.dimension.playSound("random.bow", bomb.location, { volume: 0.5, pitch: pitch });
        shrinkIfInSurvival(player, itemStack);
    }
}));
world.afterEvents.dataDrivenEntityTrigger.subscribe((event) => {
    const entity = event.entity;
    if (entity.typeId == SuppEntities.BombProjectile && event.eventId == "razz_sup:on_hit") {
        if (entity.getDynamicProperty(projectileManager.canHitTag)) {
            entity.triggerEvent("razz_sup:detonate");
            system.runTimeout(() => {
                if (entity.isValid()) {
                    // entity.remove();
                }
            });
            //break plants
            const visited = getBlocksInRadius(entity.location, 4.5, entity.dimension, block => !isFluid(block.typeId));
            visited.push(entity.dimension.getBlock(entity.location));
            visited.forEach((block) => {
                if (block && ((breakWhenPushed(block)) || isGlass(block.typeId) ||
                    block.hasTag(SuppTags.CanBombBreak))) {
                    breakBlock(block); //will pass throught walls...
                }
            });
        }
        else {
            //console.log("Bomb hit but not allowed");
        }
    }
});
