import { world } from "@minecraft/server";

export const attackCastingPreviewMethods = {
    handleAttackPreview() {
        const blockHit = this.player.getBlockFromViewDirection(
            {
                includeLiquidBlocks: this.canCastOnLiquid,
                includePassableBlocks: false,
                maxDistance: this.castingRange
            }
        );

        if (blockHit) {
            if (this.linkedAttackPreview) {
                this.moveAttackPreview(blockHit.block);

            } else {
                this.spawnAttackPreview(blockHit.block);
            }

        } else {
            if (this.linkedAttackPreview) this.removeAttackPreview();
        }
    },
    spawnAttackPreview(blockHit) {
        const spawnLoc = blockHit.offset({ x: 0, y: 1, z: 0 })?.bottomCenter() || null;
        if (!spawnLoc) return;

        const atk_prev = this.player.dimension.spawnEntity(`${this.attackPreviewTypeId}`, spawnLoc);

        if (atk_prev && atk_prev.isValid()) {
            this.linkedAttackPreview = atk_prev;
            this.onPreviewSpawn();
        }
    },
    removeAttackPreview() {
        if (this.linkedAttackPreview && this.linkedAttackPreview.isValid()) {
            this.linkedAttackPreview?.remove();
            this.linkedAttackPreview = null;
        };
    },
    moveAttackPreview(blockHit) {
        const moveLoc = blockHit.offset({ x: 0, y: 1, z: 0 })?.bottomCenter() || null;
        if (!moveLoc) return;

        this.linkedAttackPreview.teleport(moveLoc);
    }
}