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

import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.connection.DisconnectEvent;
import com.velocitypowered.api.event.connection.PostLoginEvent;
import com.velocitypowered.api.event.permission.PermissionsSetupEvent;
import com.velocitypowered.api.event.player.KickedFromServerEvent;
import com.velocitypowered.api.network.ProtocolVersion;
import com.velocitypowered.api.permission.Tristate;
import com.velocitypowered.api.proxy.Player;
import de.steamwar.linkage.Linked;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.persistent.Subserver;
import de.steamwar.sql.CheckedSchematic;
import de.steamwar.sql.SchematicType;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import de.steamwar.velocitycore.commands.*;
import de.steamwar.velocitycore.discord.DiscordBot;
import de.steamwar.velocitycore.discord.util.DiscordRanks;
import de.steamwar.velocitycore.mods.ModUtils;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;

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

@Linked
public class ConnectionListener extends BasicListener {

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

    public static void newPlayer(UUID player) {
        newPlayers.add(player);
    }

    private static final Set<String> TEAM_PERMISSIONS = Set.of("velocity.command.glist");

    @Subscribe
    public void onPermissionSetup(PermissionsSetupEvent event) {
        event.setProvider(subject -> {
            if (!(subject instanceof Player player)) {
                return perm -> Tristate.TRUE;
            }

            Set<UserPerm> perms = SteamwarUser.getOrCreate(player.getUniqueId(), player.getUsername(), ConnectionListener::newPlayer).perms();
            if (perms.contains(UserPerm.ADMINISTRATION)) {
                return perm -> Tristate.TRUE;
            } else if (perms.contains(UserPerm.TEAM)) {
                return perm -> Tristate.fromBoolean(TEAM_PERMISSIONS.contains(perm));
            } else {
                return perm -> Tristate.FALSE;
            }
        });
    }

    @Subscribe
    public void onPostLogin(PostLoginEvent event) {
        Player player = event.getPlayer();
        SteamwarUser user = SteamwarUser.get(player.getUniqueId());
        Chatter chatter = Chatter.of(player);

        if (user.hasPerm(UserPerm.CHECK)) CheckCommand.sendReminder(chatter);

        for (Subserver subserver : Subserver.getServerList()) {
            if (Subserver.isArena(subserver)) {
                chatter.system("JOIN_ARENA", new Message("JOIN_ARENA_HOVER"), ClickEvent.runCommand("/arena " + subserver.getServer().getName()), subserver.getServer().getName());
            }
        }

        for (CheckedSchematic checkedSchematic : CheckedSchematic.getUnseen(user)) {
            SchematicType type = SchematicType.fromDB(checkedSchematic.getNodeType());
            if (type == null) continue;
            if (checkedSchematic.getDeclineReason().equals("freigegeben")) {
                chatter.system("CHECK_ACCEPTED", type.name(), checkedSchematic.getSchemName());
            } else {
                chatter.system("CHECK_DECLINED", type.name(), checkedSchematic.getSchemName(), checkedSchematic.getDeclineReason());
            }

            checkedSchematic.setSeen(true);
        }

        if (newPlayers.contains(player.getUniqueId())) {
            Chatter.broadcast().system("JOIN_FIRST", player);
            newPlayers.remove(player.getUniqueId());
        }

        if (!StreamingCommand.isNotStreaming(user)) {
            chatter.system("JOIN_STREAMING");
        }

        DiscordBot.withBot(bot -> DiscordRanks.update(user));

        if (player.getProtocolVersion().noLessThan(ProtocolVersion.MINECRAFT_1_20_5)) {
            player.requestCookie(EventModeListener.EVENT_TO_SPECTATE_KEY);
        }
    }

    @Subscribe
    public void kickEvent(KickedFromServerEvent event) {
        if (event.getResult() instanceof KickedFromServerEvent.RedirectPlayer red) {
            event.setResult(KickedFromServerEvent.RedirectPlayer.create(red.getServer(), Component.empty()));
        }
    }

    @Subscribe
    public void onDisconnect(DisconnectEvent e) {
        ChallengeCommand.remove(e.getPlayer());
        MsgCommand.remove(e.getPlayer());
        ModUtils.getPlayerModMap().remove(e.getPlayer().getUniqueId());
        ModCommand.playerFilterType.remove(e.getPlayer().getUniqueId());
    }
}
