"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TeamScoreBoard = void 0;
const server_1 = require("@minecraft/server");
const gameComponent_js_1 = require("../gameComponent.js");
class TeamScoreBoard extends gameComponent_js_1.GameComponent {
    obj;
    lastRefresh = 0;
    onAttach() {
        if (!this.options)
            return;
        this.reset();
    }
    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;
    }
    reset() {
        const obj = this.getObj();
        const isDisplay = server_1.world.scoreboard.getObjectiveAtDisplaySlot(server_1.DisplaySlotId.Sidebar)
            ?.objective.id == obj.id;
        server_1.world.scoreboard.removeObjective(obj);
        if (isDisplay) {
            this.show();
        }
    }
    /**显示 */
    show() {
        if (!this.options)
            return;
        server_1.world.scoreboard.setObjectiveAtDisplaySlot(server_1.DisplaySlotId.Sidebar, {
            objective: this.getObj(),
        });
    }
    /**刷新选队计分板 */
    refreshScoreBoard() {
        if (!this.options)
            return;
        if (this.lastRefresh == server_1.system.currentTick)
            return;
        //清空计分板
        this.reset();
        //构建计分项
        const scores = [];
        const teams = this.options.teams;
        for (const team of teams) {
            let sortedTeam = team.team.getAll();
            //过滤
            if (team.teamFilter) {
                sortedTeam = sortedTeam.filter(team.teamFilter);
            }
            //排序
            if (team.teamSort) {
                sortedTeam.sort(team.teamSort);
            }
            sortedTeam.forEach((p) => {
                if (!(team.showInvalid ?? false) && !p.isValid) {
                    return;
                }
                const text = team.buildName
                    ? team.buildName(p)
                    : (team.prefix ?? "") + p.name;
                scores.push(text);
            });
        }
        //设置积分项
        const obj = this.getObj();
        for (let i = 0; i < scores.length; i++) {
            obj.setScore(scores[i], i);
        }
        this.lastRefresh = server_1.system.currentTick;
    }
    onDetach() {
        if (this.obj?.isValid) {
            server_1.world.scoreboard.removeObjective(this.obj);
        }
    }
}
exports.TeamScoreBoard = TeamScoreBoard;
