"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PlayerHealthIndicator = void 0;
const server_1 = require("@minecraft/server");
const main_js_1 = require("../../main.js");
const index_js_1 = require("../index.js");
class PlayerHealthIndicator extends index_js_1.GameComponent {
    obj;
    onAttach() {
        if (!this.options)
            return;
        this.subscribe(main_js_1.Game.events.interval, () => this.refresh(), this.options.refreshInterval);
    }
    onDetach() {
        if (this.obj?.isValid) {
            server_1.world.scoreboard.removeObjective(this.obj);
        }
    }
    getObj() {
        if (this.obj && this.obj.isValid)
            return this.obj;
        this.obj =
            server_1.world.scoreboard.getObjective(this.options.scoreBoardName) ??
                server_1.world.scoreboard.addObjective(this.options.scoreBoardName, this.options.displayName);
        return this.obj;
    }
    /**展示 */
    show() {
        const obj = this.getObj();
        server_1.world.scoreboard.setObjectiveAtDisplaySlot(server_1.DisplaySlotId.BelowName, {
            objective: obj,
        });
    }
    /**刷新计分板 */
    refresh() {
        const obj = this.getObj();
        server_1.world.getAllPlayers().forEach((p) => {
            if (!p)
                return;
            const comp = p.getComponent(server_1.EntityComponentTypes.Health);
            if (!comp)
                return;
            const cur = comp.currentValue;
            obj.setScore(p, cur);
        });
    }
}
exports.PlayerHealthIndicator = PlayerHealthIndicator;
