/*
 *   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.connection.PluginMessageEvent;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.proxy.Player;
import com.velocitypowered.api.proxy.messages.LegacyChannelIdentifier;
import com.velocitypowered.proxy.protocol.ProtocolUtils;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Mod;
import de.steamwar.velocitycore.VelocityCore;
import de.steamwar.velocitycore.listeners.BasicListener;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.util.*;
import java.util.concurrent.TimeUnit;

public class FML extends BasicListener {
    // https://wiki.vg/Minecraft_Forge_Handshake#FML_protocol_.281.7_-_1.12.29

    public static final String CHANNEL = "FML|HS";
    private final byte[] helloPacket = new byte[]{
            /* Packet type: ServerHello */ 0,
            /* FML protocol version */ 2,
            /* Override dimension (int) */ 0, 0, 0, 0
    };

    private static final Set<UUID> unlocked = new HashSet<>();

    @Subscribe
    public void onPostLogin(PostLoginEvent event) {
        Player player = event.getPlayer();

        synchronized (unlocked) {
            if (unlocked.contains(player.getUniqueId())) {
                unlocked.remove(player.getUniqueId());
                return;
            }
        }

        //if(isFML(player, "\0FML\0"))
        if (player.getProtocolVersion().lessThan(ProtocolVersion.MINECRAFT_1_13)) {
            player.sendPluginMessage(new LegacyChannelIdentifier(CHANNEL), helloPacket);
        }
    }

    public void handlePluginMessage(PluginMessageEvent event) {
        Player p = (Player) event.getSource();
        ByteBuf buf = Unpooled.wrappedBuffer(event.getData());

        if (buf.readByte() == /* ModList */ 2) {
            int numMods = ProtocolUtils.readVarInt(buf);

            List<Mod> mods = new ArrayList<>();
            for (int i = 0; i < numMods; i++) {
                String name = ProtocolUtils.readString(buf);
                ProtocolUtils.readString(buf); // version

                mods.add(Mod.getOrCreate(name, Mod.Platform.FORGE));
            }

            if (ModUtils.handleMods(p, mods)) {
                synchronized (unlocked) {
                    unlocked.add(p.getUniqueId());
                }
                Chatter.disconnect(p).system("MODS_CHECKED");
                VelocityCore.schedule(() -> {
                    synchronized (unlocked) {
                        unlocked.remove(p.getUniqueId());
                    }
                }).delay(30, TimeUnit.SECONDS).schedule();
            }
        }
    }
}
