package hu.jgj52.pvpcore.Commands;

import hu.jgj52.pvpcore.Main;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.kyori.adventure.text.event.ClickEvent;

public class ConnectCommand implements CommandExecutor, TabCompleter {
    private final Main plugin;

    public ConnectCommand(Main plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
        if (sender instanceof Player player) {
            String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+[]{};:,.<>?/";
            java.security.SecureRandom rnd = new java.security.SecureRandom();
            String key = rnd.ints(12, 0, chars.length())
                    .mapToObj(chars::charAt)
                    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
                    .toString();
            Map<String, Object> data = new HashMap<>();
            data.put("key", key);
            data.put("player", player.getUniqueId());
            data.put("timestamp", System.currentTimeMillis() + 300000);
            plugin.db.from("pvpcore_connect").eq("player", player.getUniqueId()).delete();
            plugin.db.from("pvpcore_connect").insert(data);
            player.sendMessage(
                    Component.text("A kulcsod a bejelentkezéshez: ", NamedTextColor.GREEN)
                            .append(
                                    Component.text(key, NamedTextColor.YELLOW)
                                            .clickEvent(ClickEvent.copyToClipboard(key))
                                            .hoverEvent(Component.text("Kattints a másoláshoz!", NamedTextColor.GRAY))
                            )
            );

        }
        return true;
    }

    @Override
    public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) {
        return List.of();
    }
}
