Exit Full View

Games Cupboard / gamescupboard-server / src / main / kotlin / uk / co / nickthecoder / gamescupboard / server / commands / RenameCommand.kt

package uk.co.nickthecoder.gamescupboard.server.commands

import RenamePlayer
import uk.co.nickthecoder.gamescupboard.common.CommandInfo
import uk.co.nickthecoder.gamescupboard.server.ConnectedPlayer

object RenameCommand : Command(CommandInfo("name", "Change your user-name", 1)) {
    override suspend fun run(from: ConnectedPlayer, parameters: List<String>): String? {

        val newName = parameters[0].trim()
        return if (newName.length < 3) {
            "Too short. Names must be at least 3 characters"
        } else if (newName.contains(' ')) {
            "Cannot contain spaces"
        } else if (from.game.connectedPlayers.values.firstOrNull { it.id != from.id && it.player.name == newName } != null) {
            "Cannot rename to $newName, because that name has already been taken"
        } else {
            from.game.connectedPlayers[from.player.id]?.player?.name = newName
            from.game.send(RenamePlayer(from.player.id, newName))
            null
        }
    }
}