import * as mc from "@minecraft/server";
import * as utils from "../../utils/index";
export class NavigateComponent extends utils.ActorComponent {
    constructor() {
        super(...arguments);
        this.eventBinding = this.onEventRecieved.bind(this);
    }
    onComponentAdded() {
        mc.system.afterEvents.scriptEventReceive.subscribe(this.eventBinding);
        this.target = utils.spawnEntitySafe(this.actor.dimension, this.options.navNodeId, new utils.Vector3(this.options.destination));
        utils.despawnOnReload(this.target);
        utils.mclog(`${this.actor.ActorId}'s ${this.id} timeout in ${this.actor.location.distance(this.target.location)} seconds`, this.id);
        utils.waitForEvent(this.actor.location.distance(this.target.location) * 20, () => {
            var _a;
            if ((_a = this.target) === null || _a === void 0 ? void 0 : _a.isValid())
                this.target.remove();
            this.options.onFailure();
        }, this.actor.id + this.id);
    }
    onComponentRemoved() {
        var _a;
        mc.system.afterEvents.scriptEventReceive.unsubscribe(this.eventBinding);
        if ((_a = this.target) === null || _a === void 0 ? void 0 : _a.isValid())
            this.target.remove();
        utils.abortEvents(this.actor.id + this.id);
        this.options.onFailure();
    }
    onEventRecieved(event) {
        var _a, _b;
        if (event.id === utils.addName("attack") && event.message === "attacker" && ((_a = event.sourceEntity) === null || _a === void 0 ? void 0 : _a.id) === ((_b = this.actor) === null || _b === void 0 ? void 0 : _b.id)) {
            const subScript = (subEvent) => {
                var _a, _b, _c;
                if (subEvent.id === utils.addName("attack") && subEvent.message === "victim" && ((_a = subEvent.sourceEntity) === null || _a === void 0 ? void 0 : _a.id) === ((_b = this.target) === null || _b === void 0 ? void 0 : _b.id)) {
                    mc.system.afterEvents.scriptEventReceive.unsubscribe(subScript);
                    if ((_c = this.target) === null || _c === void 0 ? void 0 : _c.isValid())
                        this.target.remove();
                    utils.abortEvents(this.actor.id + this.id);
                    this.options.onSuccess();
                }
            };
            mc.system.afterEvents.scriptEventReceive.subscribe(subScript);
            utils.waitForEvent(1, () => mc.system.afterEvents.scriptEventReceive.unsubscribe(subScript));
        }
    }
}
