"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpawnPointProtector = void 0;
const server_1 = require("@minecraft/server");
const main_js_1 = require("../../main.js");
const index_js_1 = require("../../utils/index.js");
const gameComponent_js_1 = require("../gameComponent.js");
class SpawnPointProtector extends gameComponent_js_1.GameComponent {
    onAttach() {
        const options = this.options;
        if (!options)
            return;
        // 初始设置玩家重生点
        if (options.autoSetSpawnPoint ?? true) {
            this.setPlayerSpawnPoints();
        }
        // 循环设置重生点 & 保护区域
        const interval = options.protectInterval ?? new index_js_1.Duration(10);
        this.subscribe(main_js_1.Game.events.interval, () => {
            if (options.autoSetSpawnPoint) {
                this.setPlayerSpawnPoints();
            }
            this.protectSpawnAreas();
        }, interval);
        // 出生点保护：拦截方块交互
        const protectedBlock = index_js_1.Vector3Utils.below(options.spawnPoint);
        this.subscribe(server_1.world.beforeEvents.playerInteractWithBlock, (t) => {
            if (index_js_1.Vector3Utils.isEqual(t.block.location, protectedBlock)) {
                t.cancel = true;
            }
        });
    }
    /** 设置玩家重生点 */
    setPlayerSpawnPoints() {
        const { playerGroup, spawnPoint, dimension } = this.options;
        playerGroup.forEach((p) => {
            p.player.setSpawnPoint({
                dimension,
                ...spawnPoint,
            });
        });
    }
    /** 传送所有玩家到出生点 */
    teleportAllToSpawn() {
        const { playerGroup, spawnPoint, dimension } = this.options;
        playerGroup.forEach((p) => {
            p.player.teleport(spawnPoint, { dimension });
        });
    }
    /** 循环保护出生点区域 */
    protectSpawnAreas() {
        const { spawnPoint, dimension, protectRadius } = this.options;
        if (!spawnPoint || !dimension)
            return;
        try {
            const radius = protectRadius ?? { x: 1, y: 1, z: 1 };
            const max = index_js_1.Vector3Utils.add(spawnPoint, radius);
            const min = index_js_1.Vector3Utils.subtract(spawnPoint, {
                x: radius.x,
                y: 0,
                z: radius.z,
            });
            dimension.fillBlocks(new server_1.BlockVolume(max, min), "air");
            dimension.setBlockType(index_js_1.Vector3Utils.below(spawnPoint), "bedrock");
        }
        catch (err) { }
    }
}
exports.SpawnPointProtector = SpawnPointProtector;
