package eu.mhsl.minenet.minigames.command.privileged;

import eu.mhsl.minenet.minigames.command.PrivilegedCommand;
import eu.mhsl.minenet.minigames.message.type.ChatMessage;
import eu.mhsl.minenet.minigames.message.Icon;
import eu.mhsl.minenet.minigames.util.Monitoring;

public class GcCommand extends PrivilegedCommand {
    private static long lastRun = System.currentTimeMillis();
    public GcCommand() {
        super("gc");

        setDefaultExecutor((sender, context) -> {
            long nextRun = (lastRun - (System.currentTimeMillis() - 30*1000)) / 1000;
            if(nextRun > 0) {
                new ChatMessage(Icon.ERROR).appendStatic("Please wait ").appendStatic(String.valueOf(nextRun)).appendStatic(" seconds before running GC again!").send(sender);
                return;
            }

            lastRun = System.currentTimeMillis();

            long before = Monitoring.getRamUsage();
            System.gc();
            long after = Monitoring.getRamUsage();

            new ChatMessage(Icon.SUCCESS).appendStatic("Garbage collector ran successfully!").newLine()
                    .appendStatic("before: ").appendStatic(String.valueOf(before)).appendStatic("MB").newLine()
                    .appendStatic("now: ").appendStatic(String.valueOf(after)).appendStatic("MB").newLine()
                    .appendStatic("difference: ").appendStatic(String.valueOf(before-after)).appendStatic("MB")
                    .send(sender);
        });
    }
}
