package de.kif.backend.view

import de.kif.backend.prefix
import de.kif.common.model.Permission
import de.kif.common.model.User
import io.ktor.html.Template
import kotlinx.html.*

class MenuTemplate(
    private val url: String,
    private val user: User?
) : Template<FlowContent> {

    override fun FlowContent.apply() {
        val tab = Tab.lookup(url)

        nav("menu") {
            div("container") {
                div("menu-left") {
                    a("$prefix/", classes = if (tab == null) "active" else null) {
                        +"Neuigkeiten"
                    }
                    a("$prefix/calendar", classes = if (tab == Tab.CALENDAR) "active" else null) {
                        +"Zeitplan"
                    }
                }
                div("menu-right") {
                    span("menu-icon") {
                        i("material-icons") { +"menu" }
                    }
                    val user = user
                    div("menu-content") {
                        if (user == null) {
                            a("$prefix/account", classes = if (tab == Tab.LOGIN) "active" else null) {
                                +"Einloggen"
                            }
                        } else {
                            if (user.checkPermission(Permission.WORK_GROUP)) {
                                a("$prefix/workgroups", classes = if (tab == Tab.WORK_GROUP) "active" else null) {
                                    +"Arbeitskreise"
                                }
                            }
                            if (user.checkPermission(Permission.ROOM)) {
                                a("$prefix/rooms", classes = if (tab == Tab.ROOM) "active" else null) {
                                    +"Räume"
                                }
                            }
                            if (user.checkPermission(Permission.USER)) {
                                a("$prefix/users", classes = if (tab == Tab.USER) "active" else null) {
                                    +"Nutzer"
                                }
                            }
                            a("$prefix/account", classes = if (tab == Tab.ACCOUNT) "active" else null) {
                                +user.username
                            }
                        }
                    }
                }
            }
        }
    }

    enum class Tab {
        NEWS, CALENDAR, ACCOUNT, WORK_GROUP, ROOM, USER, LOGIN;

        companion object {
            private val lookup = values().toList().associateBy { it.name.take(4).toLowerCase() }

            fun lookup(url: String): Tab? {
                return lookup[url.take(4)]
            }
        }
    }
}
