import * as mc from "@minecraft/server";
import * as utils from "../../utils/index";
import * as comp from "../components/index";
import { BotBase } from "../bot";
export class AnglerBot extends BotBase {
    get Owner() {
        if (this.owner)
            return this.owner;
        const tame = this.getComponent("tameable");
        if (tame && tame.tamedToPlayerId) {
            const owner = utils.getAllPlayersSafe().find(player => player.id === tame.tamedToPlayerId);
            this.owner = owner;
            return owner;
        }
    }
    onConstructed() {
        super.onConstructed();
        //this.addActorComponent(comp.VirtualInventoryComponent);
        this.addActorComponent(comp.AutotameComponent);
        this.addActorComponent(comp.AttackComponent, {
            type: "melee",
            cooldown: 2,
            damage: 0,
            duration: {
                dmgTime: 0.25,
                endTime: 1.0
            },
            onHit: this.onAttackFish.bind(this),
        });
        utils.waitForEvent(1, () => {
            this.eventBinding = this.onEventRecieved.bind(this);
            mc.system.afterEvents.scriptEventReceive.subscribe(this.eventBinding);
        });
    }
    destructor() {
        super.destructor();
        if (this.eventBinding)
            mc.system.afterEvents.scriptEventReceive.unsubscribe(this.eventBinding);
    }
    onAttackFish(victim) {
        this.dimension.playSound(utils.addName("entity.angler_bot.attack"), this.location);
        victim.runCommand(`loot spawn ~ ~ ~ kill @s`);
        utils.getEntitiesSafe(victim.dimension, { location: victim.location, maxDistance: 2, type: "minecraft:item" }).forEach(item => {
            const itemComp = item.getComponent("item");
            if (itemComp && this.Inventory) {
                this.Inventory.addItem(itemComp.itemStack);
            }
            item.remove();
        });
        utils.waitForEvent(1, victim.remove.bind(victim));
    }
    onEventRecieved(event) {
        var _a, _b;
        if (event.id === utils.addName("reach_owner") && ((_a = event.sourceEntity) === null || _a === void 0 ? void 0 : _a.id) === this.id && ((_b = this.Owner) === null || _b === void 0 ? void 0 : _b.isValid())) {
            //this.giveInventory(this.Owner);
        }
    }
    giveInventory(player) {
        const virtualInventory = this.getActorComponent(comp.VirtualInventoryComponent);
        if (virtualInventory) {
            virtualInventory.getAllItems(true).forEach(item => {
                if (player.Inventory.emptySlotsCount > 0) {
                    player.playSound("random.pop");
                    player.Inventory.addItem(item);
                }
                else {
                    this.dimension.spawnItem(item, this.location);
                }
            });
        }
    }
}
utils.Actor.makeActors({ type: "ldz_240927:angler_bot" }, AnglerBot);
