package eu.mhsl.minenet.minigames;

import eu.mhsl.minenet.minigames.api.HttpServer;
import eu.mhsl.minenet.minigames.command.Commands;
import eu.mhsl.minenet.minigames.handler.Listeners;
import eu.mhsl.minenet.minigames.lang.Languages;
import eu.mhsl.minenet.minigames.server.tasks.TablistUpdateTask;
import net.minestom.server.MinecraftServer;
import net.minestom.server.extras.bungee.BungeeCordProxy;
import net.minestom.server.extras.lan.OpenToLAN;
import net.minestom.server.extras.velocity.VelocityProxy;
import net.minestom.server.timer.TaskSchedule;
import org.spongepowered.configurate.ConfigurateException;
import org.spongepowered.configurate.ConfigurationNode;
import org.spongepowered.configurate.yaml.YamlConfigurationLoader;

import java.util.Objects;
import java.util.logging.Logger;

public class Main {
    /**
     * Starts minenet minigames services
     */
    private final static Logger logger = Logger.getGlobal();
    public static ConfigurationNode globalConfig;

    public static void main(String[] args) throws ConfigurateException {
        //noinspection ResultOfMethodCallIgnored
        Resource.values(); // This initializes and preloads the enum and extracts the resources
        Languages.getInstance(); //Preload languages into the jvm

        globalConfig = YamlConfigurationLoader
                .builder()
                .path(Resource.CONFIG.getPath())
                .build()
                .load();

        ConfigurationNode serverConfig = globalConfig.node("server");

        logger.info("Initialize Minecraft server...");

        MinecraftServer server = MinecraftServer.init();
//        MinestomPvP.init();

        MinecraftServer.setBrandName("mhsl.eu - minenet - credits to minestom");
        MinecraftServer.setCompressionThreshold(serverConfig.node("compression-threshold").getInt(0));
        System.setProperty("minestom.chunk-view-distance", String.valueOf(serverConfig.node("view-distance").getInt()));

        Commands.values();
        Listeners.values();
        new HttpServer();

        MinecraftServer.getSchedulerManager().scheduleTask(new TablistUpdateTask(), TaskSchedule.tick(20), TaskSchedule.tick(20));

        logger.info("Starting Minecraft server ... ");

        if(serverConfig.node("open-to-lan").getBoolean()) OpenToLAN.open();

        if(globalConfig.node("bungeecord", "enabled").getBoolean()) BungeeCordProxy.enable();

        if(globalConfig.node("velocity", "enabled").getBoolean()) {
            VelocityProxy.enable(Objects.requireNonNull(globalConfig.node("velocity", "secret").getString()));
        }

        server.start("0.0.0.0", serverConfig.node("port").getInt(25565));
        System.gc();

        MinecraftServer.getSchedulerManager().scheduleNextTick(() -> logger.info("Minecraft server is now running!"));
    }
}
