/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2024  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.Reflection;
import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.core.Core;
import de.steamwar.core.FlatteningWrapper;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

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

public class SWScoreboard8 implements SWScoreboard {
    private static final Reflection.Field<String> scoreboardName = Reflection.getField(FlatteningWrapper.scoreboardObjective, String.class, 0);
    private static final Reflection.Field<Integer> scoreboardAction = Reflection.getField(FlatteningWrapper.scoreboardObjective, int.class, Core.getVersion() > 15 ? 3 : 0);
    private static final Class<?> scoreboardDisplayEnum = Reflection.getClass("net.minecraft.world.scores.criteria.IScoreboardCriteria$EnumScoreboardHealthDisplay");
    private static final Reflection.Field<?> scoreboardDisplayType = Reflection.getField(FlatteningWrapper.scoreboardObjective, scoreboardDisplayEnum, 0);
    private static final Object displayTypeIntegers = scoreboardDisplayEnum.getEnumConstants()[0];

    private static final Reflection.Field<String> scoreName = Reflection.getField(FlatteningWrapper.scoreboardScore, String.class, 0);
    private static final Reflection.Field<String> scoreScoreboardName = Reflection.getField(FlatteningWrapper.scoreboardScore, String.class, 1);
    private static final Reflection.Field<Integer> scoreValue = Reflection.getField(FlatteningWrapper.scoreboardScore, int.class, 0);

    private static final HashMap<Player, ScoreboardCallback> playerBoards = new HashMap<>(); //Object -> Scoreboard | Alle Versionen in der Map!
    private static int toggle = 0; // Scoreboard 0 updates while scoreboard 1 is presenting. toggle marks the current active scoreboard

    private static final String SIDEBAR = "Sidebar";
    private static final Object[] DELETE_SCOREBOARD = new Object[2];
    private static final Object[] DISPLAY_SIDEBAR = new Object[2];

    static {
        Class<?> scoreboardDisplayObjective = Reflection.getClass("net.minecraft.network.protocol.game.PacketPlayOutScoreboardDisplayObjective");
        Reflection.Field<String> scoreboardDisplayName = Reflection.getField(scoreboardDisplayObjective, String.class, 0);
        Reflection.Field<Integer> scoreboardDisplaySlot = Reflection.getField(scoreboardDisplayObjective, int.class, 0);
        for(int id = 0; id < 2; id++) {
            DELETE_SCOREBOARD[id] = Reflection.newInstance(FlatteningWrapper.scoreboardObjective);
            scoreboardName.set(DELETE_SCOREBOARD[id], SIDEBAR + id);
            scoreboardAction.set(DELETE_SCOREBOARD[id], 1); //1 to remove

            DISPLAY_SIDEBAR[id] = Reflection.newInstance(scoreboardDisplayObjective);
            scoreboardDisplayName.set(DISPLAY_SIDEBAR[id], SIDEBAR + id);
            scoreboardDisplaySlot.set(DISPLAY_SIDEBAR[id], 1); // 1 = Sidebar
        }

        Bukkit.getScheduler().runTaskTimer(Core.getInstance(), () -> {
            toggle ^= 1; // Toggle between 0 and 1

            for(Map.Entry<Player, ScoreboardCallback> scoreboard : playerBoards.entrySet()) {
                Player player = scoreboard.getKey();
                ScoreboardCallback callback = scoreboard.getValue();

                TinyProtocol.instance.sendPacket(player, DELETE_SCOREBOARD[toggle]);
                TinyProtocol.instance.sendPacket(player, createSidebarPacket(callback.getTitle()));
                for(Map.Entry<String, Integer> score : callback.getData().entrySet()){
                    TinyProtocol.instance.sendPacket(player, createScorePacket(score.getKey(), score.getValue()));
                }

                Bukkit.getScheduler().runTaskLater(Core.getInstance(), () -> {
                    if(!player.isOnline())
                        return;
                    TinyProtocol.instance.sendPacket(player, DISPLAY_SIDEBAR[toggle]);
                }, 2);
            }
        }, 10, 5);
    }

    public boolean createScoreboard(Player player, ScoreboardCallback callback) {
        playerBoards.put(player, callback);
        return true;
    }

    public void removeScoreboard(Player player) {
        if(playerBoards.remove(player) == null || !player.isOnline())
            return;

        TinyProtocol.instance.sendPacket(player, DELETE_SCOREBOARD[toggle]);
    }

    private static Object createSidebarPacket(String name){
        Object packet = Reflection.newInstance(FlatteningWrapper.scoreboardObjective);
        scoreboardName.set(packet, SIDEBAR + toggle);
        scoreboardAction.set(packet, 0); //0 to create
        FlatteningWrapper.impl.setScoreboardTitle(packet, name);
        scoreboardDisplayType.set(packet, displayTypeIntegers);
        return packet;
    }

    private static Object createScorePacket(String name, int value){
        Object packet = Reflection.newInstance(FlatteningWrapper.scoreboardScore);
        scoreName.set(packet, name);
        scoreScoreboardName.set(packet, SIDEBAR + toggle);
        scoreValue.set(packet, value);
        FlatteningWrapper.impl.setScoreAction(packet);
        return packet;
    }
}
