package de.steamwar.commands.user

import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.Context
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.help
import com.github.ajalt.mordant.table.table
import de.steamwar.db.joinedOr
import de.steamwar.db.useDb
import de.steamwar.sql.SteamwarUser
import de.steamwar.sql.SteamwarUserTable
import de.steamwar.sql.Team
import org.jetbrains.exposed.v1.core.eq
import org.jetbrains.exposed.v1.core.like

class UserSearchCommand : CliktCommand("search") {
    val query by argument().help("Name, Id, UUID or DiscordId")

    override val printHelpOnEmptyArgs = true

    override fun help(context: Context): String =
        "Search for users"

    override fun run() =
        useDb {
            val users = SteamwarUser.find {
                joinedOr(
                    SteamwarUserTable.username like "%$query%",
                    SteamwarUserTable.uuid like "%$query%",
                    query.toLongOrNull()?.let { SteamwarUserTable.discordId eq it },
                    query.toIntOrNull()?.let { SteamwarUserTable.id eq it }
                )
            }

            val teams = mutableMapOf<Int, Team>()

            echo(table {
                header { row("Id", "Username", "UUID", "Team", "DiscordId") }
                body {
                    users.map { row(it.id.value, it.userName, it.uuid, teams.computeIfAbsent(it.team) { teamId -> Team.byId(teamId) }.teamName, it.discordId) }
                }
            })
        }
}
