You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.7 KiB
106 lines
2.7 KiB
import db.PlayerTimeDB |
|
import java.time.Duration |
|
import java.time.LocalDateTime |
|
import java.util.UUID |
|
import models.Player |
|
|
|
/** |
|
* A service to hold the all player that are currently playing |
|
* It should only be used as Singleton @see Kotlin objects |
|
* |
|
* @property db the DB implementation which should be used to persist the state |
|
* @property playerMap Holds all online players |
|
*/ |
|
open class PlayerService(private val db: PlayerTimeDB) { |
|
|
|
private val playerMap = mutableMapOf<UUID, Player>() |
|
|
|
/** |
|
* Adds the player to the playerMap. |
|
* It creates an new player if it's no persisted and adds/refreshes the join time |
|
* |
|
* @param uuid the actual uuid of a player |
|
* @param playerName for debugging because with the new api playerNames are not longer unique |
|
*/ |
|
fun addPlayer(uuid: UUID, playerName: String) { |
|
val player: Player = if (db.findByID(uuid)) { |
|
val player = db.readPlayer(uuid) |
|
player.joinTime = LocalDateTime.now() |
|
player |
|
} else { |
|
val player = Player(uuid, playerName) |
|
db.createPlayer(player) |
|
player |
|
} |
|
playerMap[uuid] = player |
|
} |
|
|
|
/** |
|
* Removes a player from the map and persists its status |
|
* |
|
*@param uuid players uuid |
|
*/ |
|
fun removePlayer(uuid: UUID) { |
|
persistPlayer(uuid) |
|
playerMap.remove(uuid) |
|
} |
|
|
|
/** |
|
* Wrapper for the map to prevent directly exposition |
|
* |
|
* @return status of the inner map |
|
*/ |
|
fun containsPlayer(uuid: UUID): Boolean { |
|
return playerMap.containsKey(uuid) |
|
} |
|
|
|
/** |
|
* Wrapper for the map to prevent directly exposition |
|
* |
|
* @return status of the inner map |
|
*/ |
|
fun isEmpty(): Boolean { |
|
return playerMap.isEmpty() |
|
} |
|
|
|
/** |
|
* Updates and writes the current status to the db |
|
* |
|
* @param uuid player uuid |
|
*/ |
|
fun persistPlayer(uuid: UUID) { |
|
val duration = timePlayed(uuid) |
|
val player = getPlayer(uuid) |
|
player.playTime = Duration.from(duration) |
|
db.writePlayer(player) |
|
} |
|
|
|
/** |
|
* Persists all player |
|
*/ |
|
fun persistAllPlayer() { |
|
for ((uuid, _) in playerMap) { |
|
persistPlayer(uuid) |
|
} |
|
} |
|
|
|
/** |
|
* Returns the player with that uuid |
|
* |
|
* @param uuid player uuid |
|
*/ |
|
fun getPlayer(uuid: UUID): Player { |
|
return playerMap[uuid]!! |
|
} |
|
|
|
/** |
|
* Returns the player time including the old time |
|
* |
|
* @param uuid player uuid |
|
*/ |
|
fun timePlayed(uuid: UUID): Duration { |
|
val player = getPlayer(uuid) |
|
val duration = Duration.between(player.joinTime, LocalDateTime.now()) |
|
return Duration.from(player.playTime).plus(duration) |
|
} |
|
}
|
|
|