package uk.co.nickthecoder.gamescupboard.server.commands
import CommandError
import CommandOk
import uk.co.nickthecoder.gamescupboard.common.CommandInfo
import uk.co.nickthecoder.gamescupboard.server.ConnectedPlayer
/**
* Players can send commands by typing in the chat input.
*
* NOTE, the player prefixes the command name with ":", but the colon is NOT part of [name].
* It is only there to indicate that this is a command, and not a chat message.
*/
abstract class Command(
val info: CommandInfo,
/**
* If true, then this command is run when the game first starts, and when the game is reset.
* It must accept zero arguments.
*/
val isInitialiser: Boolean = false
) {
val name: String get() = info.name
val minParameters: Int get() = info.minParameters
val maxParameters: Int get() = info.maxParameters
abstract suspend fun run(from: ConnectedPlayer, parameters: List<String>): String?
suspend fun checkAndRun(from: ConnectedPlayer, parameters: List<String>) {
if (parameters.size < minParameters) {
from.send(CommandError("Expected at least $minParameters parameters"))
return
}
if (parameters.size > maxParameters) {
from.send(CommandError("Expected at most $maxParameters parameters"))
return
}
val errorMessage = run(from, parameters)
if (errorMessage == null) {
from.send(CommandOk)
} else {
from.send(CommandError(errorMessage))
}
}
override fun toString() = "$name $minParameters..$maxParameters isInitialiser=$isInitialiser"
}