package org.atmospheregames.network;
import com.google.gson.JsonObject;
import com.jonahseguin.drink.CommandService;
import com.jonahseguin.drink.Drink;
import lombok.Getter;
import org.atmospheregames.network.command.NetworkCommand;
import org.atmospheregames.network.heartbeat.HeartbeatThread;
import org.atmospheregames.network.redis.RedisClient;
import org.atmospheregames.network.tps.TPSRunnable;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;

public final class Network extends JavaPlugin {

    @Getter private final CommandService commandService = Drink.get(this);

    @Getter private TPSRunnable tpsRunnable;
    @Getter private RedisClient redisClient;
    @Getter private HeartbeatThread heartbeatThread;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        Bukkit.getScheduler().scheduleSyncRepeatingTask(this, tpsRunnable = new TPSRunnable(), 0L, 1L);

        this.redisClient = new RedisClient(this);
        this.heartbeatThread = new HeartbeatThread(this);
        this.heartbeatThread.start();

        commandService.register(new NetworkCommand(this), "network");
        commandService.registerCommands();
    }

    @Override
    public void onDisable() {
        sendServerUpdateMessage(false);
        redisClient.destroy();
    }

    public void sendServerUpdateMessage(boolean online) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.addProperty("server", getConfig().getString("SERVER-NAME"));
        jsonObject.addProperty("online", online);
        jsonObject.addProperty("whitelisted", Bukkit.getServer().hasWhitelist());
        jsonObject.addProperty("onlinePlayers", Bukkit.getOnlinePlayers().size());
        jsonObject.addProperty("onlinePlayerLimit", Bukkit.getMaxPlayers());
        jsonObject.addProperty("ticksPerSecond", tpsRunnable.getTPS());

        redisClient.write(jsonObject);
    }
}
