import { system, world } from "@minecraft/server";
import { couplingData, dimensions, getPullingCar, isRail } from "./trainsAddOn";
import { queryBlock, sendDebugMessage, vectorAbove } from "./JM_Utils";

system.runInterval(function tnt() {
    try {
        dimensions.forEach(element => {
            const dimension = world.getDimension(element)
            // dimension.getEntities({type:"minecraft:tnt"}).forEach(tnt => {
            //     tnt.teleport(createVector("-29 -58 48"))
            //     tnt.clearVelocity()
            // })
            dimension.getEntities({type:"lifeboat_ta:tnt_wagon"}).forEach(car => {
                const curBlock = queryBlock(car.location,dimension)
                if (!curBlock) return
                const below = queryBlock(vectorAbove(curBlock.location,-1),dimension)
                if (!below) return
                if (!isRail(curBlock) && !isRail(below)) splode(car)
            })
        })
    } catch (error) {
        // ignore
    }
})

function splode(splode,killEmpty=true) {
    if (splode.hasTag("lb_ta:splodin")) return
    splode.addTag("lb_ta:splodin")
    const pulledBy = getPullingCar(splode.id,splode.dimension)
    if (pulledBy) couplingData(pulledBy).decouple(true)
    const empty = splode.dimension.spawnEntity("lifeboat_ta:log_trainvagon",splode.location)
    const lookDir = splode.getViewDirection()
    sendDebugMessage(`${JSON.stringify(lookDir)}`)
    empty.setRotation(splode.getRotation())
    if (killEmpty) empty.kill()
    const locations = []
    for (let i = 0; i < 4; i++) {
        locations.push({
            x: splode.location.x - (2 * lookDir.x) + (i * lookDir.x),
            y: splode.location.y,
            z: splode.location.z - (2 * lookDir.z) + (i * lookDir.z)
        })
    }
    locations.forEach(location => {
        splode.dimension.spawnEntity("tnt",location)
        // splode.dimension.createExplosion(location,3 + Math.floor(Math.random() * 4))
    })
    splode.remove()
}

system.afterEvents.scriptEventReceive.subscribe(event => {
    if (!event.sourceEntity) return
    if (event.sourceEntity.typeId !== "lifeboat_ta:tnt_wagon") return
    if (event.id === "lifeboat_ta:explode") {
        splode(event.sourceEntity)
    } else if (event.id === "lifeboat_ta:ignite") splode(event.sourceEntity,false)
})