/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.features.script.lua.libs;

import de.steamwar.bausystem.features.world.BauScoreboard;
import de.steamwar.bausystem.utils.ScoreboardElement;
import de.steamwar.linkage.Linked;
import org.bukkit.entity.Player;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.VarArgFunction;

@Linked
public class ScoreboardLib implements LuaLib {

    @Override
    public String name() {
        return "scoreboard";
    }

    @Override
    public LuaTable get(Player player) {
        LuaTable luaTable = new LuaTable();

        LuaTable groups = new LuaTable();
        for (ScoreboardElement.ScoreboardGroup group : ScoreboardElement.ScoreboardGroup.values()) {
            groups.set(group.name(), group.ordinal());
        }
        luaTable.set("group", groups);

        luaTable.set("element", new VarArgFunction() {
            @Override
            public Varargs invoke(Varargs varargs) {
                if (varargs.narg() < 2) {
                    return NIL;
                }
                String elementKey = varargs.arg(1).checkjstring();
                ScoreboardElement.ScoreboardGroup elementGroup = ScoreboardElement.ScoreboardGroup.values()[varargs.arg(2).checkint()];
                int priority = varargs.narg() > 2 ? varargs.arg(2).checkint() : Integer.MAX_VALUE;

                return new VarArgFunction() {
                    @Override
                    public Varargs invoke(Varargs args) {
                        if (args.narg() == 0) {
                            BauScoreboard.setAdditionalElement(player, elementKey, elementGroup, priority, null);
                        } else {
                            BauScoreboard.setAdditionalElement(player, elementKey, elementGroup, priority, args.arg1().checkjstring());
                        }
                        return NIL;
                    }
                };
            }
        });
        return luaTable;
    }
}
