/*
 *   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 de.steamwar.linkage.Linked;
import de.steamwar.velocitycore.Node;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.UserPerm;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Linked
public class StatCommand extends SWCommand {

    public StatCommand() {
        super("stat", UserPerm.ADMINISTRATION, "stats");
    }

    @Register
    public void genericCommand(Chatter sender) {
        Map<String, Integer> serverCount = new HashMap<>();
        try {
            Process process = new ProcessBuilder("ps", "x").start();
            new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(s -> {
                if (!s.contains("--port"))
                    return;
                serverCount.compute(
                        s.contains("ssh -L") ? s.substring(s.indexOf("ssh -L") + 6).split(" ")[2] : "sw",
                        (server, count) -> (count != null ? count : 0) + 1
                );
            });
        } catch (Exception e) {
            throw new SecurityException(e.getMessage(), e);
        }

        Node.forEach(node -> sender.prefixless("STAT_SERVER", node.getName(), node.belowLoadLimit(), serverCount.getOrDefault(node.getName(), 0)));
    }
}
