import * as mc from "@minecraft/server";
import * as vector from "../utils/vector";
import * as selectors from "../utils/selectors";

import { ATTACK_DAMAGE } from "./bluff";

export function eventBehavior(event) {
    const entity = event.entity;

    if (event.eventId === 'register') {
        if (entity.getDynamicProperty("hf_mzs:has_appeared") !== undefined) {
            entity.triggerEvent("break");
            return;
        }
        mc.system.runTimeout(() => {
            const targets = selectors.union({
                location: entity.location,
                maxDistance: 1.3,
                excludeFamilies: ['inanimate', 'hf_mzs_bluff']
            }, ['mob', 'player'], entity.dimension, entity.id)
            for (let target of targets) {
                if (!target.isValid())
                    continue;
                const dir = {
                    x: entity.getDynamicProperty("hf_mzs:x_dir"),
                    z: entity.getDynamicProperty("hf_mzs:z_dir")
                };
                target.applyKnockback(dir.x, dir.z, 2, 4);
                if (entity.getDynamicProperty("hf_mzs:shooter")) {
                    target.applyDamage(ATTACK_DAMAGE, {
                        cause: "entityAttack",
                        damagingEntity: mc.world.getEntity(entity.getDynamicProperty("hf_mzs:shooter"))
                    });
                }
                else {
                    target.applyDamage(ATTACK_DAMAGE, {
                        cause: "entityAttack"
                    });
                }
            }
        }, 2);
        const pos = {
            x: Math.floor(entity.location.x) + 0.5,
            y: entity.location.y,
            z: Math.floor(entity.location.z) + 0.5,
        }
        entity.runCommand(`/fill ${vector.string(pos)} ${vector.string(pos)} hf_mzs:bluff_boulder [] replace air`);
        entity.runCommand("/playsound hf_mzs:mob.bluff.rock_appear @a[r=16] ~~~");
        entity.runCommand("/particle hf_mzs:bluff_boulder2 ~~~");

        entity.setDynamicProperty("hf_mzs:has_appeared", true);
        return;
    }
    if (event.eventId === 'break') {
        entity.runCommand("/playsound hf_mzs:mob.bluff.rock_explode @a[r=16] ~~~");
        entity.runCommand("/particle hf_mzs:bluff_boulder_break ~~~");
        const pos = {
            x: Math.floor(entity.location.x) + 0.5,
            y: entity.location.y,
            z: Math.floor(entity.location.z) + 0.5,
        }
        entity.runCommand(`/fill ${vector.string(pos)} ${vector.string(pos)} air [] replace hf_mzs:bluff_boulder`);
        entity.remove();
        return;
    }
}