package de.kif.frontend.views.board

import de.kif.common.formatTimeDiff
import de.kif.common.model.Schedule
import de.kif.frontend.views.overview.getByClassOrCreate
import de.westermann.kobserve.event.EventHandler
import de.westermann.kwebview.View
import de.westermann.kwebview.createHtmlView
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.get

class BoardSchedule(
    view: HTMLElement,
    startTime: Long = 0L,
    endTime: Long = 0L
) : View(view) {
    val colorViewContainer = view.getByClassOrCreate<HTMLDivElement>("board-schedule-color")
    val colorView = colorViewContainer.getByClassOrCreate<HTMLSpanElement>("bsc")
    val timeView = view.getByClassOrCreate<HTMLDivElement>("board-schedule-time")
    val nameView = view.getByClassOrCreate<HTMLDivElement>("board-schedule-name")
    val roomView = view.getByClassOrCreate<HTMLDivElement>("board-schedule-room")


    val clockViewContainer = view.getByClassOrCreate<HTMLDivElement>("board-schedule-clock")
    val clockView = clockViewContainer.getByClassOrCreate<HTMLElement>("material-icons", "i").also {
        it.textContent = "alarm"
    }

    private val startTime: Long = timeView.dataset["startTime"]?.toLongOrNull() ?: startTime
    private val endTime: Long = timeView.dataset["endTime"]?.toLongOrNull() ?: endTime

    val onRemove = EventHandler<Unit>()

    fun updateTime(now: Long) {
        timeView.textContent = when {
            startTime >= now -> "Start ${formatTimeDiff(startTime, now)}"
            endTime >= now -> "Ende ${formatTimeDiff(endTime, now)}"
            else -> {
                onRemove.emit(Unit)
                "---"
            }
        }

        classList["board-schedule-running"] = now in startTime..endTime
    }

    companion object {
        fun create(schedule: Schedule, referenceTime: Long, now: Long): BoardSchedule {
            val startTime = ((schedule.getAbsoluteStartTime() * 60 * 1000) + referenceTime)
            val endTime = ((schedule.getAbsoluteEndTime() * 60 * 1000) + referenceTime)

            val entry = BoardSchedule(createHtmlView(), startTime, endTime)

            if (schedule.workGroup.track?.color != null) {
                entry.colorView.style.backgroundColor = schedule.workGroup.track.color.toString()
            }
            entry.nameView.textContent = schedule.workGroup.name
            entry.roomView.textContent = schedule.room.name

            entry.updateTime(now)

            return entry
        }
    }
}
