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

import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.EventFight;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.velocitycore.VelocityCore;

import java.net.InetSocketAddress;
import java.util.List;

public class ServerSwitchCommand extends SWCommand {

    private final RegisteredServer server;
    private final boolean isSpectateServer;

    public ServerSwitchCommand(String cmd, String name, boolean isSpectateServer, String... aliases) {
        super(cmd, null, aliases);
        server = VelocityCore.getProxy().getServer(name).orElseThrow();
        this.isSpectateServer = isSpectateServer;
    }

    @Register
    public void genericCommand(PlayerChatter sender) {
        if (isSpectateServer && sender.getPlayer().getProtocolVersion().noLessThan(ProtocolVersion.MINECRAFT_1_20_5)) {
            SteamwarUser user = SteamwarUser.get(sender.getPlayer().getUniqueId());
            List<EventFight> activeFights = EventFight.getActiveFights();

            if (activeFights.stream()
                    .anyMatch(fight -> fight.getTeamRed() == user.getTeam() || fight.getTeamBlue() == user.getTeam())) {
                sender.getPlayer().transferToHost(new InetSocketAddress("steamwar.de", 25566));
                return;
            }
        }

        sender.getPlayer().createConnectionRequest(server).fireAndForget();
    }
}
