package de.walamana.views

import de.walamana.models.Ministrant
import de.walamana.models.MinistrantenDao
import de.walamana.models.SimplifiedMinistrant
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*

fun Route.configureMinistrantenRoutes() {
    route("/ministranten") {
        get {
            val data = MinistrantenDao.allMinistranten();
            call.respond(data)
        }
        put {
            val data = call.receive<Ministrant>()
            val passwordHash = data.passwordHash ?: return@put
            val ministrant = MinistrantenDao.createMinistrant(
                data.username,
                passwordHash,
                data.firstname,
                data.lastname,
                data.birthday,
                data.privileges
            )
            call.respond(mapOf("id" to ministrant?.id))
        }
        patch {
            // TODO: Access only by admin
            val simple = false
            if(simple) {
                val data = call.receive<SimplifiedMinistrant>()
                val changed = MinistrantenDao.updateMinistrant(
                    id = data.id,
                    username = data.username,
                    firstname = data.firstname,
                    lastname = data.lastname
                )
            }else{
                val data = call.receive<Ministrant>()
                val changed = MinistrantenDao.updateMinistrant(
                    data.id,
                    data.username,
                    null,
                    data.firstname,
                    data.lastname,
                    data.birthday,
                    data.privileges
                )
            }
            call.respond(HttpStatusCode.OK)
        }
        delete {
            val id = call.request.queryParameters["id"]?.toInt() ?: TODO("fail")
            MinistrantenDao.deleteMinistrant(id)
            call.respond(HttpStatusCode.OK)
        }
    }
}
