package de.walamana.plugins

import de.walamana.models.GottesdienstGroups
import de.walamana.models.Gottesdienste
import de.walamana.models.Marks
import de.walamana.models.Ministranten
import io.ktor.server.application.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.transactions.transaction

fun Application.configureDatabases() {
    val driverClassName = environment.config.property("database.driver").getString()
    val jdbcURL = environment.config.property("database.url").getString()
    val user = environment.config.propertyOrNull("database.user")?.getString()
    val password = environment.config.propertyOrNull("database.password")?.getString()

    println("Using database driver $driverClassName")

    val database = if(user != null && password != null )
        Database.connect(jdbcURL, driverClassName, user, password)
    else
        Database.connect(jdbcURL, driverClassName)

    transaction {
        SchemaUtils.create(Ministranten)
        SchemaUtils.create(GottesdienstGroups)
        SchemaUtils.create(Gottesdienste)
        SchemaUtils.create(Marks)
    }
}

suspend fun <T> dbQuery(block: suspend Transaction.() -> T): T =
    newSuspendedTransaction(Dispatchers.IO) { block() }
