import { system, world } from "@minecraft/server";
import { createVector, vectorAbove, vectorAdd, vectorMultiplyByNumber, vectorRoundDown, vectorToString } from "./JM_Utils";

world.afterEvents.entityDie.subscribe(deathEvent => {
    const dead = deathEvent.deadEntity
    const damager = deathEvent.damageSource.damagingEntity
    if (!dead || !dead.isValid) return
    if (dead.hasTag("lb_as:creeper_head")) {
        dead.dimension.createExplosion(dead.location, 3)
    } else if (dead.hasTag("lb_as:skeleton_skull")) {
        for (let index = 0; index < 100; index++) {
            const thing = dead.dimension.spawnEntity(
                "arrow",
                vectorAbove(dead.location, 0.25)
            )
            const angle = Math.random() * 2 * Math.PI;
            const radius = Math.sqrt(Math.random());
            thing.applyImpulse(createVector(
                Math.cos(angle) * radius,
                0.4,
                Math.sin(angle) * radius
            ))
            system.runTimeout(() => {
                if (thing && thing.isValid) thing.remove()
            }, 20)
        }
    } else if (dead.hasTag("lb_as:dragon_head")) {
        world.structureManager.place("lb_as:potion", dead.dimension, vectorRoundDown(dead.location), { includeBlocks: false })
    } else if (damager?.isValid) {
        if (damager.hasTag("lb_as:piglin_head")) {
            damager.setProperty("lb_as:celebrating", Math.floor(Math.random() * 3) + 3)
        }
    }
})

world.afterEvents.entityHurt.subscribe(hurtEvent => {
    const damager = hurtEvent.damageSource.damagingEntity
    if (!damager || !damager.isValid) return
    const hurty = hurtEvent.hurtEntity
    if (damager.hasTag("lb_as:wither_skeleton_skull")) {
        hurty.addEffect("wither", 20 * 10)
    } else if (damager.hasTag("lb_as:zombie_head")) {
        if (world.getTimeOfDay() <= 12541 || world.getTimeOfDay() >= 23460 || Math.random() < 0.4) return
        // zombies start on fire from 23460 to 12541 (inclusive)
        hurty.setOnFire(4)
    }
})

system.runInterval(() => {
    const dimensionIds = []
    world.getAllPlayers().forEach(player => {
        if (!dimensionIds.includes(player.dimension.id)) {
            dimensionIds.push(player.dimension.id)
            player.dimension.getEntities({
                type: "lb_as:armor",
                tags: ["lb_as:piglin_head"],
                propertyOptions: [
                    {
                        propertyId: "lb_as:celebrating",
                        value: { greaterThanOrEquals: 1 }
                    },
                    {
                        propertyId: "lb_as:has_target",
                        value: false
                    }
                ]
            }).forEach(piglarmor => {
                piglarmor.setProperty("lb_as:celebrating", piglarmor.getProperty("lb_as:celebrating") - 1)
            })
        }
    })
}, 20)