import { Vector3, expandingCubeOperation, getBlockCountInVolume, isSolid, waitForTicks } from "../../utils/index";
import { Task } from "./task";
export class FindNearbyBlockTask extends Task {
    async start() {
        return super.start();
    }
    async performTask() {
        if (!this.options.blocks.some(block => getBlockCountInVolume(this.npc.Entity.location.subtract(2.5), this.npc.Entity.location.add(2.5), this.npc.Entity.dimension, block) > 0)) {
            return { outcome: "failed" };
        }
        let interactLocation = new Vector3(0);
        let navigationLocation = new Vector3(0);
        let foundBlock = false;
        await expandingCubeOperation(this.npc.Entity.location.round(), async (location) => {
            const groundBlock = this.npc.Entity.dimension.getBlock(location);
            const interactBlock = groundBlock === null || groundBlock === void 0 ? void 0 : groundBlock.above();
            if (this.options.blocks.some(block => groundBlock === null || groundBlock === void 0 ? void 0 : groundBlock.permutation.matches(block.block)) && this.isValid(interactBlock)) {
                const neighborBlocks = [interactBlock.north(), interactBlock.south(), interactBlock.east(), interactBlock.west()];
                const validNeighbor = neighborBlocks.find(neighbor => { var _a; return this.isValid(neighbor) && ((_a = neighbor.above()) === null || _a === void 0 ? void 0 : _a.isAir) && isSolid(neighbor.below()); });
                if (validNeighbor) {
                    interactLocation = new Vector3(location).add({ x: 0.5, y: 1, z: 0.5 });
                    navigationLocation = new Vector3(validNeighbor.location).add({ x: 0.5, y: 0, z: 0.5 });
                    foundBlock = true;
                    return true;
                }
            }
            return false;
        }, async () => {
            await waitForTicks(1);
            return false;
        }, {
            min: 1,
            max: 5
        });
        if (foundBlock) {
            return { outcome: "succeeded", data: { interactLocation, navigationLocation } };
        }
        else {
            return { outcome: "failed" };
        }
    }
    async cleanupTask() {
    }
    isValid(block) {
        if (!block)
            return false;
        if (block.isAir)
            return true;
        const whitelist = [
            "minecraft:snow_layer",
        ];
        if (whitelist.some(name => block.permutation.matches(name)))
            return true;
        return false;
    }
}
