package de.walamana.views

import de.walamana.models.GottesdienstGroup
import de.walamana.models.GottesdienstGroupDao
import de.walamana.models.GottesdienstGroups
import de.walamana.service.PlanDao
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.util.*

fun Route.configurePlanRoutes() {
    route("/plan") {
        get {
            val principal = call.principal<JWTPrincipal>()
            val isAnonymous = principal == null
            val id = call.parameters.getOrFail("id").toInt()
            val plan = PlanDao.constructPlan(id, isAnonymous = isAnonymous);
            call.respond(plan)
        }
    }
    route("/groups") {
        get {
            val offset = call.parameters.get("offset")?.toLong() ?: 0
            val amount = call.parameters.get("amount")?.toInt() ?: 10
            val groups = GottesdienstGroupDao.getPlans(amount, offset)
            call.respond(groups)
        }
        post {
            val group = call.receive<GottesdienstGroup>()
            val res = GottesdienstGroupDao.createPlan(group.from, group.to) ?: TODO("fail")
            call.respond(res)
        }
        patch {
            val group = call.receive<GottesdienstGroup>()
            val res = GottesdienstGroupDao.updatePlan(group) ?: TODO("fail")
            call.respond(res)
        }
        delete {
            val id = call.parameters.getOrFail("id").toInt()
            val res = GottesdienstGroupDao.deletePlan(id)
            call.respond(hashMapOf("success" to res))
        }
    }
}
