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

import java.util.HashSet;
import java.util.Set;

import de.steamwar.linkage.Linked;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

import com.comphenix.tinyprotocol.TinyProtocol;
import com.mojang.authlib.GameProfile;

import de.steamwar.core.ProtocolWrapper;
import de.steamwar.fightsystem.ArenaMode;
import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.fight.Fight;
import de.steamwar.fightsystem.fight.FightPlayer;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependentListener;
import de.steamwar.fightsystem.states.StateDependentTask;

@Linked
public class Spectator implements Listener {

    private final Set<Player> pseudoSpectator = new HashSet<>();

    public Spectator() {
        new StateDependentListener(ArenaMode.AntiTest, FightState.All, this);
        new StateDependentTask(ArenaMode.AntiTest, FightState.All, this::pseudoSpectatorCheck, 1, 1);
    }

    @EventHandler(priority = EventPriority.MONITOR)
    public void handlePlayerJoin(PlayerJoinEvent e) {
        Player player = e.getPlayer();

        if(player.getGameMode() == GameMode.SPECTATOR)
            gameModeChange(player, GameMode.SPECTATOR);
    }

    @EventHandler
    public void onGameModeChange(PlayerGameModeChangeEvent e) {
        gameModeChange(e.getPlayer(), e.getNewGameMode());
    }

    @SuppressWarnings("deprecation")
    private void gameModeChange(Player player, GameMode gameMode) {
        if (gameMode == GameMode.SPECTATOR) {
            for(Player p : Bukkit.getServer().getOnlinePlayers()) {
                if(p.getUniqueId() != player.getUniqueId())
                    p.hidePlayer(player);
            }
        } else {
            for(Player p : Bukkit.getServer().getOnlinePlayers()) {
                if(p.getUniqueId() != player.getUniqueId())
                    p.showPlayer(player);
            }
        }
    }

    @EventHandler
    public void playerQuit(PlayerQuitEvent e) {
        pseudoSpectator.remove(e.getPlayer());
    }

    private void pseudoSpectatorCheck() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            if (player.getGameMode() != GameMode.SPECTATOR) {
                pseudoSpectator.remove(player);
                continue;
            }

            if (Config.isReferee(player))
                continue;

            FightPlayer fightPlayer = Fight.getFightPlayer(player);
            if (fightPlayer == null || !fightPlayer.getTeam().getExtendRegion().playerInRegion(player.getLocation())) {
                if (pseudoSpectator.add(player))
                    pseudoSpectator(player, true);
            } else {
                if (pseudoSpectator.remove(player))
                    pseudoSpectator(player, false);
            }
        }
    }

    private static void pseudoSpectator(Player player, boolean enable) {
        TinyProtocol.instance.sendPacket(player, ProtocolWrapper.impl.playerInfoPacketConstructor(ProtocolWrapper.PlayerInfoAction.GAMEMODE, new GameProfile(player.getUniqueId(), player.getName()), enable ? GameMode.CREATIVE : GameMode.SPECTATOR));
    }
}
