/*
 *   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.scoreboard;

import de.steamwar.core.Core;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;

import java.util.HashMap;
import java.util.Map;

public class SWScoreboard {
    public static final SWScoreboard impl = new SWScoreboard();

    private static final HashMap<Player, ScoreboardCallback> playerBoards = new HashMap<>();
    private static final String SIDEBAR = "sw-sidebar";

    static {
        Bukkit.getScheduler().runTaskTimer(Core.getInstance(), () -> {
            for (Map.Entry<Player, ScoreboardCallback> scoreboard : playerBoards.entrySet()) {
                render(scoreboard.getKey(), scoreboard.getValue());
            }
        }, 10, 5);
    }

    private static void render(Player player, ScoreboardCallback callback) {
        if (player.getScoreboard().getObjective(SIDEBAR) != null) {
            player.getScoreboard().getObjective(SIDEBAR).unregister();
        }

        Objective objective = player.getScoreboard().registerNewObjective(SIDEBAR, "dummy", Component.text(callback.getTitle()));
        objective.setAutoUpdateDisplay(true);
        objective.setDisplaySlot(DisplaySlot.SIDEBAR);

        callback.getData().forEach((text, score) -> objective.getScore(text).setScore(score));
    }

    public boolean createScoreboard(Player player, ScoreboardCallback callback) {
        Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
        player.setScoreboard(scoreboard);

        render(player, callback);

        playerBoards.put(player, callback);
        return true;
    }

    public void removeScoreboard(Player player) {
        player.getScoreboard().getObjective(SIDEBAR).unregister();
        playerBoards.remove(player);
    }
}
