import { system, world, BlockPermutation, EntityDamageCause } from "@minecraft/server";
import * as attackUtils from "../attackUtils.js";

export function stoneWallSetBlocks(wallEntity) {
    if (!wallEntity.isValid()) return;

    const dim = wallEntity.dimension;
    const positions = wallEntity.getDynamicPropertyIds().filter(id => id.startsWith("oct_eg:wall_pos_"));
    const wallHeight = wallEntity.getDynamicProperty("oct_eg:wall_height") ?? 2;

    if (positions.length === 0 || !dim) return;

    // Parse all positions once
    const targets = [];
    for (const id of positions) {
        const posJson = wallEntity.getDynamicProperty(id);
        if (!posJson) continue;

        const pos = JSON.parse(posJson);
        for (let h = 0; h < wallHeight; h++) {
            targets.push({ x: pos.x, y: pos.y + h, z: pos.z });
        }
    }

    function* blockPlacingGenerator(locations, dimension, wallEntity) {
        for (const loc of locations) {
            const block = dimension.getBlock(loc);
            if (block?.isAir || block?.isLiquid) {
                block.setPermutation(BlockPermutation.resolve("minecraft:barrier"));
            }
            yield;
        }
    }

    system.runJob(blockPlacingGenerator(targets, dim, wallEntity));

}
export function stoneWallRemoveBlocks(wallEntity) {
    if (!wallEntity.isValid()) return;

    const dim = wallEntity.dimension;
    const positions = wallEntity.getDynamicPropertyIds().filter(id => id.startsWith("oct_eg:wall_pos_"));
    const wallHeight = wallEntity.getDynamicProperty("oct_eg:wall_height") ?? 2;

    if (positions.length === 0 || !dim) return;

    const targets = [];
    for (const id of positions) {
        const posJson = wallEntity.getDynamicProperty(id);
        if (!posJson) continue;

        const pos = JSON.parse(posJson);
        for (let h = 0; h < wallHeight; h++) {
            targets.push({ x: pos.x, y: pos.y + h, z: pos.z });
            wallEntity.dimension.spawnParticle("oct_eg:undead_minion.dirt", pos);
            wallEntity.dimension.spawnParticle("oct_eg:heavy_punch.smoke", pos);
        }
    }

    function* blockRemovingGenerator(locations, dimension, wallEntity) {
        for (const loc of locations) {
            const block = dimension.getBlock(loc);
            if (block && block.typeId === "minecraft:barrier") {
                block.setPermutation(BlockPermutation.resolve("minecraft:air"));
            }
            yield;
        }
        // wallEntity?.remove();
    }

    system.runJob(blockRemovingGenerator(targets, dim, wallEntity));
    wallEntity.dimension.playSound("octovon.eg.gauntlet.geo.stone_wall.despawn", wallEntity.location);
}

export function stoneWallTick(wallEntity) {
    const doesDamage = wallEntity.getDynamicProperty("oct_eg:does_damage") ?? false;
    if (!doesDamage) return;


    const owner = wallEntity.getComponent("minecraft:tameable")?.tamedToPlayer;
    const damage = wallEntity.getDynamicProperty("oct_eg:wall_damage") ?? 3;
    //world.sendMessage('damage ' + damage);

    const positionIds = wallEntity
        .getDynamicPropertyIds()
        .filter(id => id.startsWith("oct_eg:wall_pos_"));

    // Collect all scan locations (each wall block + one above)
    const scanLocations = [];
    for (const id of positionIds) {
        const posJson = wallEntity.getDynamicProperty(id);
        if (!posJson) continue;
        const { x, y, z } = JSON.parse(posJson);

        // ground block
        scanLocations.push({ x, y, z });
        // one block above
        scanLocations.push({ x, y: y + 1, z });
    }

    for (const loc of scanLocations) {

        for (const entity of attackUtils.getValidTargetsInRange(wallEntity, {
            startLocation: loc,
            maxDistance: 1.5,
            excludedEntities: [owner],
        })) {
            attackUtils.applyModifiedDamage(entity, damage, {
                cause: EntityDamageCause.contact
            });
        }
    }
}