import { EntityComponentTypes, system, world } from "@minecraft/server"

const GOLEM_TYPE_ID = "lb_ga:lightning_rod_golem"

system.runInterval(() => {
    const dimensionIds = []
    // loop through all players to find which dimensions are currently active
    world.getAllPlayers().forEach(player => {
        if (!dimensionIds.includes(player.dimension.id)) dimensionIds.push(player.dimension.id)
    })
    // for each active dimension, find variant 1 lightning rod golems (variant 1 = in rain during a thunderstorm, variant 0 = not in rain or no thunderstorm active)
    dimensionIds.forEach(dimensionId => {
        const dimension = world.getDimension(dimensionId)
        dimension.getEntities({ type: GOLEM_TYPE_ID }).forEach(golem => {
            // to return to melee state
            if (golem.getProperty('lb_ga:charge') == 0) golem.triggerEvent("lb_ga:normal_attack")

            try { //this was added because sometimes you would get the error "cannot read property 'value' of undefined."
                const variant = golem.getComponent(EntityComponentTypes.Variant).value

                if (variant === 0) return
                // remaining golems are all valid thunderstorm golems!
                // energizes the golem only the property == 0
                if (Math.random() <= 0.05 && golem.getProperty('lb_ga:charge') == 0) {
                    try {
                        dimension.spawnEntity("minecraft:lightning_bolt", golem.location)
                    } catch (chunkError) {
                        return
                    }
                }
            } catch (error) {
                return
            }
        })
    })
}, 20)

//This golem spawns an entity within itself to track nearby enemies and reduce property values.
world.afterEvents.projectileHitBlock.subscribe((event) => {
    const projectile = event.projectile;
    const golem = event.source;

    if (projectile?.typeId !== "lb_ga:lightning_rod_projectile") return;

    projectile.remove();

    golem.dimension.getEntities({ families: ["monster"], closest: 4, location: golem.location, maxDistance: 15 }).forEach((monster) => {
        golem.dimension.spawnEntity("minecraft:lightning_bolt", monster.location);
    })
    golem.setProperty('lb_ga:charge', golem.getProperty('lb_ga:charge') -1)
    // console.warn(`${golem.getProperty('lb_ga:charge')}`)
});

//If golem is damaged by lightning bolt, charge it.
world.afterEvents.entityHurt.subscribe(e => {
    const entity = e.hurtEntity
    const source = e.damageSource.cause
    if (entity.typeId !== 'lb_ga:lightning_rod_golem') return
    if (source !== "lightning") return
    if (entity.getProperty('lb_ga:charge') == 0) {
        entity.setProperty('lb_ga:charge', 10)
        entity.triggerEvent("lb_ga:ranged_attack")
        //Heal golem when hit by lightning
        const healthComp = entity.getComponent('minecraft:health')
        const currentHealth = healthComp.currentValue
        if (currentHealth > 0) healthComp.resetToDefaultValue()
    }
})