import * as mc from '@minecraft/server'

const fumerolleCooldowns = new Map();
const triggerExceptions = ['ash_dino', 'cyd_dino:boss', 'empy_spell', 'trice_spell', 'ptera_spell'];

export const fumerolleBlockBehavior = {
    onRandomTick(e) {
        const { block, dimension } = e
        const location = block.center()
        const ashEnabled = mc.world.getDynamicProperty('cyd_dino:enabled_ash') ?? true

        if (!ashEnabled) return;


        dimension.spawnParticle('cyd_dino:lava_burst_1', location)
        dimension.spawnParticle('cyd_dino:lava_burst_2', location)
        dimension.spawnParticle('cyd_dino:lava_burst_3', location)
    },
    /**
     * 
     * @param {mc.BlockComponentTickEvent} e 
     */
    onTick(e) {
        try {
            const { block, dimension } = e
            const location = block.center()

            dimension.getEntities({
                location: block.above().center(),
                maxDistance: 1
            }).forEach(entity => {
                for (const exception of triggerExceptions) {
                    if (entity.getComponent(mc.EntityComponentTypes.TypeFamily)?.hasTypeFamily(exception)) return;
                }
                entity.applyDamage(3, { cause: mc.EntityDamageCause.fireTick })
            });


            dimension.getEntities({
                location: block.above().center(),
                maxDistance: 3
            }).forEach(entity => {
                for (const exception of triggerExceptions) {
                    if (entity.getComponent(mc.EntityComponentTypes.TypeFamily)?.hasTypeFamily(exception)) return;
                }
                entity.addEffect("poison", 2 * mc.TicksPerSecond, { amplifier: 2 })
            })

            const ashEnabled = mc.world.getDynamicProperty('cyd_dino:enabled_ash') ?? true
            if (!ashEnabled) return;

            const currentTick = mc.system.currentTick;
            const key = `${dimension.id}:${block.location.x}:${block.location.y}:${block.location.z}`;
            const nextAllowed = fumerolleCooldowns.get(key) ?? 0;

            if (currentTick < nextAllowed) return;

            const minTicks = 7 * mc.TicksPerSecond;
            const maxTicks = 24 * mc.TicksPerSecond;
            const delay = minTicks + Math.floor(Math.random() * (maxTicks - minTicks + 1));
            fumerolleCooldowns.set(key, currentTick + delay);

            const chance = 0.5;
            if (Math.random() > chance) return;

            dimension.spawnParticle('cyd_dino:volcanic_smoke_1', { x: location.x, y: location.y + 0.5, z: location.z })
            dimension.spawnParticle('cyd_dino:volcanic_smoke_2', { x: location.x, y: location.y + 0.5, z: location.z })
        } catch (err) {
        }
    },
    onPlace(e) {
        const block = e.block
        updateConnections(block)
        updateAdjacentBlocks(block)
    },
    onPlayerDestroy(e) {
        const block = e.block
        updateAdjacentBlocks(block)
    }
}

/**
 * @param {mc.Block} block
 */
function updateConnections(block) {
    try {
        const blockId = 'cyd_dino:fumerolle_block'

        const north = block.north()
        const south = block.south()
        const east = block.east()
        const west = block.west()
        const northEast = north.east()
        const northWest = north.west();
        const southEast = south.east();
        const southWest = south.west();

        block.setPermutation(
            block.permutation
                .withState('cyd_dino:connected_north', north?.typeId === blockId)
                .withState('cyd_dino:connected_south', south?.typeId === blockId)
                .withState('cyd_dino:connected_east', east?.typeId === blockId)
                .withState('cyd_dino:connected_west', west?.typeId === blockId)
                .withState('cyd_dino:connected_north_east', northEast?.typeId === blockId)
                .withState('cyd_dino:connected_north_west', northWest?.typeId === blockId)
                .withState('cyd_dino:connected_south_east', southEast?.typeId === blockId)
                .withState('cyd_dino:connected_south_west', southWest?.typeId === blockId)
        )
        const permutations = block.permutation.getAllStates && block.permutation.getAllStates();
    } catch (error) {

    }
}
function updateAdjacentBlocks(block) {
    try {
        const blockId = 'cyd_dino:fumerolle_block'

        // gather the 8 neighboring positions (3x3 area around the block, excluding center)
        const north = block.north()
        const south = block.south()
        const east = block.east()
        const west = block.west()

        const northEast = north.east();
        const northWest = north.west();
        const southEast = south.east();
        const southWest = south.west();

        const adjacentBlocks = [
            north,
            south,
            east,
            west,
            northEast,
            northWest,
            southEast,
            southWest
        ]

        adjacentBlocks.forEach(adjacentBlock => {
            if (adjacentBlock?.typeId === blockId) {
                const north = adjacentBlock.north()
                const south = adjacentBlock.south()
                const east = adjacentBlock.east()
                const west = adjacentBlock.west()
                const northEast = north.east();
                const northWest = north.west();
                const southEast = south.east();
                const southWest = south.west();

                adjacentBlock.setPermutation(
                    adjacentBlock.permutation
                        .withState('cyd_dino:connected_north', north?.typeId === blockId)
                        .withState('cyd_dino:connected_south', south?.typeId === blockId)
                        .withState('cyd_dino:connected_east', east?.typeId === blockId)
                        .withState('cyd_dino:connected_west', west?.typeId === blockId)
                        .withState('cyd_dino:connected_north_east', northEast?.typeId === blockId)
                        .withState('cyd_dino:connected_north_west', northWest?.typeId === blockId)
                        .withState('cyd_dino:connected_south_east', southEast?.typeId === blockId)
                        .withState('cyd_dino:connected_south_west', southWest?.typeId === blockId)
                )
            }
        })
    } catch (error) {

    }
}