package de.kif.frontend.views.calendar

import de.kif.frontend.repository.RoomRepository
import de.westermann.kwebview.ViewCollection
import de.westermann.kwebview.createHtmlView
import org.w3c.dom.HTMLDivElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.set

class CalendarRow(calendar: CalendarBody, view: HTMLElement) : ViewCollection<CalendarCell>(view) {
    val day = calendar.day

    val time = dataset["time"]?.toIntOrNull() ?: 0

    init {
        wrapContent {
            CalendarCell(this, it)
        }

        RoomRepository.onCreate {
            +CalendarCell.create(this, it)
        }
        RoomRepository.onDelete { id ->
            find { it.roomId == id }?.let(this@CalendarRow::remove)
        }
    }

    companion object {
        suspend fun create(calendar: CalendarBody, time: Int): CalendarRow {
            val view = createHtmlView<HTMLDivElement>()
            view.classList.add("calendar-row")
            view.dataset["time"] = time.toString()

            val row = CalendarRow(calendar, view)

            val rowHeader = createHtmlView<HTMLElement>()
            rowHeader.classList.add("calendar-cell")
            if (time % 60 == 0) {
                val span = createHtmlView<HTMLSpanElement>()

                val t = (time % (60 * 24)).let {
                    if (it < 0) it + 60 * 24 else it
                }
                val hours = (t / 60).toString().padStart(2, '0')
                span.textContent = "$hours:00"

                rowHeader.appendChild(span)
            }
            row.html.appendChild(rowHeader)

            row.html

            val rooms = RoomRepository.all()

            for (room in rooms) {
                if (room.id != null) {
                    row += CalendarCell.create(row, room.id)
                }
            }

            return row
        }
    }
}
