Files
src
build.gradle.kts
manifest.kod
Code
38 2,867
src/main/kotlin/com/lf/medals/leaderboard/LeaderboardManager.kt
package com.lf.medals.leaderboard
import com.lf.medals.LFMedals
import com.lf.medals.api.PlayerTopMedalGainEvent
import com.lf.medals.api.PlayerTopMedalLoseEvent
import com.lf.medals.utils.ColorUtils
import me.clip.placeholderapi.PlaceholderAPI
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitRunnable
import org.bukkit.scheduler.BukkitTask
import java.util.Calendar
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
class LeaderboardManager(private val plugin: LFMedals) {
private val entries = HashMap<String, LeaderboardEntry>()
private val currentHolders = ConcurrentHashMap<String, UUID>()
private val tasks = HashMap<String, BukkitTask>()
private val baselines = ConcurrentHashMap<String, ConcurrentHashMap<UUID, Double>>()
private val lastResetMonth = ConcurrentHashMap<String, Int>()
private val lastNotifyTime = ConcurrentHashMap<String, Long>()
private var monthlyCheckTask: BukkitTask? = null
fun load() {
stopAll()
entries.clear()
baselines.clear()
lastResetMonth.clear()
lastNotifyTime.clear()
val section = plugin.config.getConfigurationSection("leaderboards") ?: return
for (key in section.getKeys(false)) {
val s = section.getConfigurationSection(key) ?: continue
val rawMode = s.getString("placeholder-mode", "VALUE")?.uppercase() ?: "VALUE"
val mode = if (rawMode == "DELTA") "DELTA" else "VALUE"
val rawReset = s.getString("reset-type", "NONE")?.uppercase() ?: "NONE"
val resetType = if (rawReset == "MONTHLY") "MONTHLY" else "NONE"
val notifyCooldown = s.getLong("notify-cooldown", 300L)
val entry = LeaderboardEntry(
id = key,
placeholder = s.getString("placeholder", "") ?: "",
updateInterval = s.getLong("update-interval", 60L),
position = s.getInt("position", 1),
medalId = s.getString("medal-id", "") ?: "",
enabled = s.getBoolean("enabled", true),
mode = mode,
resetType = resetType,
notifyCooldown = notifyCooldown
)
entries[key] = entry
if (mode == "DELTA" || resetType == "MONTHLY") baselines[key] = ConcurrentHashMap()
if (resetType == "MONTHLY") {
lastResetMonth[key] = Calendar.getInstance().get(Calendar.MONTH)
}
}
for (entry in entries.values) {
if (entry.enabled) scheduleTask(entry)
}
if (plugin.server.pluginManager.isPluginEnabled("PlaceholderAPI")) {
captureInitialBaselines()
}
scheduleMonthlyCheck()
plugin.logger.info("Loaded ${entries.size} leaderboard entries.")
}
private fun scheduleMonthlyCheck() {
monthlyCheckTask?.cancel()
val hasMonthly = entries.values.any { it.resetType == "MONTHLY" }
if (!hasMonthly) return
monthlyCheckTask = object : BukkitRunnable() {
override fun run() {
val currentMonth = Calendar.getInstance().get(Calendar.MONTH)
for ((id, entry) in entries) {
if (entry.resetType != "MONTHLY") continue
val storedMonth = lastResetMonth[id] ?: currentMonth
if (storedMonth != currentMonth) {
lastResetMonth[id] = currentMonth
performMonthlyReset(id, entry)
}
}
}
}.runTaskTimerAsynchronously(plugin, 1200L, 1200L)
}
private fun performMonthlyReset(leaderboardId: String, entry: LeaderboardEntry) {
baselines[leaderboardId]?.clear()
if (plugin.server.pluginManager.isPluginEnabled("PlaceholderAPI")) {
val baselineMap = baselines.getOrPut(leaderboardId) { ConcurrentHashMap() }
for (player in Bukkit.getOnlinePlayers()) {
baselineMap[player.uniqueId] = parsePlaceholder(player, entry.placeholder)
}
}
val autoMedal = plugin.medalManager.getAutoMedal(entry.medalId) ?: return
val oldHolder = currentHolders.remove(leaderboardId)
Bukkit.getScheduler().runTask(plugin, Runnable {
if (oldHolder != null) {
val loseEvent = PlayerTopMedalLoseEvent(oldHolder, autoMedal, leaderboardId)
Bukkit.getPluginManager().callEvent(loseEvent)
}
val resetMsg = plugin.langManager.get(
"leaderboard.monthly-reset",
"medal" to autoMedal.name,
"position" to entry.position.toString()
)
if (resetMsg.isNotBlank()) {
val colored = ColorUtils.colorize(plugin.langManager.getPrefix() + resetMsg)
Bukkit.broadcastMessage(colored)
}
})
}
private fun captureInitialBaselines() {
object : BukkitRunnable() {
override fun run() {
val onlinePlayers = Bukkit.getOnlinePlayers().toList()
for ((id, entry) in entries) {
if (entry.mode != "DELTA" && entry.resetType != "MONTHLY") continue
val baselineMap = baselines.getOrPut(id) { ConcurrentHashMap() }
for (player in onlinePlayers) {
if (!baselineMap.containsKey(player.uniqueId)) {
val value = parsePlaceholder(player, entry.placeholder)
baselineMap[player.uniqueId] = value
}
}
}
}
}.runTaskAsynchronously(plugin)
}
private fun parsePlaceholder(player: org.bukkit.entity.Player, placeholder: String): Double {
return try {
PlaceholderAPI.setPlaceholders(player, placeholder)
.replace(",", "").replace(" ", "").toDouble()
} catch (_: NumberFormatException) {
0.0
}
}
private fun scheduleTask(entry: LeaderboardEntry) {
val task = object : BukkitRunnable() {
override fun run() {
updateLeaderboard(entry)
}
}.runTaskTimerAsynchronously(plugin, 20L, entry.updateInterval * 20L)
tasks[entry.id] = task
}
private fun updateLeaderboard(entry: LeaderboardEntry) {
if (!plugin.server.pluginManager.isPluginEnabled("PlaceholderAPI")) return
val autoMedal = plugin.medalManager.getAutoMedal(entry.medalId) ?: return
val onlinePlayers = Bukkit.getOnlinePlayers().toList()
if (onlinePlayers.isEmpty()) return
val scores = HashMap<UUID, Double>()
if (entry.mode == "DELTA" || entry.resetType == "MONTHLY") {
val baselineMap = baselines.getOrPut(entry.id) { ConcurrentHashMap() }
for (player in onlinePlayers) {
val current = parsePlaceholder(player, entry.placeholder)
val baseline = baselineMap.getOrPut(player.uniqueId) { current }
scores[player.uniqueId] = (current - baseline).coerceAtLeast(0.0)
}
} else {
for (player in onlinePlayers) {
scores[player.uniqueId] = parsePlaceholder(player, entry.placeholder)
}
}
val sorted = scores.entries.sortedByDescending { it.value }
val newHolderEntry = sorted.getOrNull(entry.position - 1)
val newHolder = newHolderEntry?.key
val oldHolder = currentHolders[entry.id]
if (oldHolder == newHolder) return
val now = System.currentTimeMillis()
val lastNotify = lastNotifyTime[entry.id] ?: 0L
val cooldownMs = entry.notifyCooldown * 1000L
val canNotify = (now - lastNotify) >= cooldownMs
if (canNotify) lastNotifyTime[entry.id] = now
Bukkit.getScheduler().runTask(plugin, Runnable {
val oldHolderName = if (oldHolder != null) Bukkit.getOfflinePlayer(oldHolder).name ?: oldHolder.toString() else null
val newHolderName = if (newHolder != null) Bukkit.getOfflinePlayer(newHolder).name ?: newHolder.toString() else null
if (oldHolder != null && oldHolder != newHolder) {
currentHolders.remove(entry.id)
val loseEvent = PlayerTopMedalLoseEvent(oldHolder, autoMedal, entry.id)
Bukkit.getPluginManager().callEvent(loseEvent)
if (canNotify) {
val broadcastMsg = plugin.langManager.get(
"leaderboard.broadcast-lose",
"loser" to (oldHolderName ?: "?"),
"winner" to (newHolderName ?: "?"),
"position" to entry.position.toString(),
"medal" to autoMedal.name
)
if (broadcastMsg.isNotBlank()) {
Bukkit.broadcastMessage(ColorUtils.colorize(plugin.langManager.getPrefix() + broadcastMsg))