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

import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.player.ServerPostConnectEvent;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.linkage.Linked;
import de.steamwar.persistent.Bauserver;
import de.steamwar.persistent.Builderserver;
import de.steamwar.persistent.Subserver;
import de.steamwar.velocitycore.VelocityCore;
import de.steamwar.velocitycore.commands.DevCommand;
import de.steamwar.velocitycore.listeners.BasicListener;
import de.steamwar.velocitycore.listeners.PluginMessage;

import java.util.Arrays;

@Linked
public class ReplayMod extends BasicListener {
    // https://gist.github.com/Johni0702/2547c463e51f65f312cb
    // https://github.com/ReplayMod/replay-restrictions/blob/master/bungeecord/src/main/java/de/johni0702/replay/restrictions/BungeeCordPlugin.java
    // https://github.com/ReplayMod/ReplayMod/blob/stable/src/main/java/com/replaymod/core/utils/Restrictions.java

    private final byte[] restrict;

    public ReplayMod() {
        restrict = PluginMessage.genStreamPacket(out -> {
            for (String restriction : Arrays.asList("no_xray", "no_noclip", "only_first_person", "only_recording_player")) {
                byte[] bytes = restriction.getBytes();
                out.writeByte(bytes.length);
                out.write(bytes);
                out.writeBoolean(true); // restrict
            }
        });
    }

    @Subscribe
    public void onPlayerJoin(ServerPostConnectEvent event) {
        Player player = event.getPlayer();
        if (VelocityCore.get().getConfig().lobbyserver().getPlayersConnected().contains(player)) return;

        Subserver subserver = Subserver.getSubserver(player.getCurrentServer().orElseThrow().getServerInfo());
        if (subserver instanceof Builderserver || (subserver instanceof Bauserver bauserver && bauserver.getOwner().equals(player.getUniqueId())) || DevCommand.getDevServers().containsValue(player.getCurrentServer().orElseThrow().getServer())) {
            return;
        }

        PluginMessage.send(player, "Replay|Restrict", "replaymod:restrict", restrict);
    }
}
