import {
    MolangVariableMap,
    MinecraftBlockTypes,
    MinecraftItemTypes,
    BlockAreaSize,
    ItemStack,
    world,
    Player,
    system,
    MinecraftEntityTypes,
    EnchantmentList,
    DynamicPropertiesDefinition
}
from "@minecraft/server";
import {
    ActionFormData,
    MessageFormData,
    ModalFormData,
    ActionFormResponse
}
from "@minecraft/server-ui";
system.runInterval(runInterval)

world.afterEvents.entityDie.subscribe((entitydie) => {
    if (entitydie.deadEntity.typeId == `minecraft: player`) {
        entitydie.deadEntity.runCommandAsync(`function player_death`)
    }
})

function score(player, objective) {
    try {
        return world.scoreboard.getObjective(objective)
            .getScore(player.scoreboardIdentity)
    } catch (e) {
        return 0;
    }
}




function runInterval() {
    for (const player of world.getPlayers()) {
        player.runCommand("scoreboard objectives add ts:vx dummy")
        player.runCommand("scoreboard objectives add ts:vy dummy")
        player.runCommand("scoreboard objectives add ts:vz dummy")
        for (const entity of player.dimension.getEntities()) {
            if (entity.hasTag("tse_st")) {
                if (!entity.hasTag("tse_over")) {
                    if (!entity.hasTag("tse")) {
                        let velocity = entity.getVelocity()
                        let scoreboardVelocity = {
                            x: parseInt(velocity.x * 1000),
                            y: parseInt(velocity.y * 1000),
                            z: parseInt(velocity.z * 1000)
                        };
                        entity.runCommand("scoreboard players set @s ts:vx " + scoreboardVelocity.x)
                        entity.runCommand("scoreboard players set @s ts:vy " + scoreboardVelocity.y)
                        entity.runCommand("scoreboard players set @s ts:vz " + scoreboardVelocity.z)
                        entity.addTag("tse")
                    }
                } else {
                    entity.removeTag("tse")
                    entity.removeTag("tse_st")
                    entity.removeTag("tse_over")
                    entity.applyImpulse({
                        x: score(entity, "ts:vx") / 1000,
                        y: score(entity, "ts:vy") / 1000,
                        z: score(entity, "ts:vz") / 1000
                    });
                }
            }
        }
    }
    for (const player of world.getPlayers()) {
        for (const entity of player.dimension.getEntities()) {
            if (entity.hasTag("gd_m_ed")) {
                if (entity.isFalling) {
                    entity.runCommand("damage @s 1")
                    entity.runCommand("effect @s fatal_poison 2 1")
                    entity.runCommand("effect @s slowness 2 0")
                    entity.runCommand("playsound gd_m_e @a[r=4] ~~~")
                    entity.runCommand("particle jjba:gd_m_e ~~0.5~")
                }
            }
        }
    }
}