import * as mc from "@minecraft/server";
import { GlobalNamespace, SafetyCheckedEntity, waitForLoopEvent } from "../../utils/index";
import { Task } from "./task";
export class MoveToTargetTask extends Task {
    async performTask() {
        const tagName = `${GlobalNamespace.Namespace}target${this.npc.Entity.id}`;
        this.npc.Entity.dimension.getEntities({ type: this.options.navTargetTypeId, tags: [tagName] }).forEach(oldNode => oldNode.remove());
        const target = new SafetyCheckedEntity(this.npc.Entity.dimension.spawnEntity(this.options.navTargetTypeId, this.options.location));
        target.addTag(tagName);
        this.npc.Entity.triggerEvent(this.options.startNavEvent);
        const distance = this.npc.Entity.location.distance(target.location);
        const abortTime = mc.system.currentTick + ((distance + 5) * 20);
        await waitForLoopEvent(5, () => this.npc.Entity.location.distance(target.location) <= this.options.stopDistance || mc.system.currentTick > abortTime, this.id);
        if (mc.system.currentTick > abortTime)
            this.abort();
        this.shouldAbort();
        target.remove();
        this.npc.Entity.triggerEvent(this.options.endNavEvent);
        return { outcome: "succeeded" };
    }
    async cleanupTask() {
        const tagName = `${GlobalNamespace.Namespace}target${this.npc.Entity.id}`;
        this.npc.Entity.dimension.getEntities({ type: this.options.navTargetTypeId, tags: [tagName] }).forEach(oldNode => oldNode.remove());
        this.npc.Entity.triggerEvent(this.options.endNavEvent);
    }
}
