package de.kif.frontend.views.board

import de.kif.common.formatDateTime
import de.kif.frontend.iterator
import de.westermann.kwebview.interval
import org.w3c.dom.HTMLElement
import org.w3c.dom.get
import kotlin.browser.document
import kotlin.js.Date

fun initBoard() {
    val boardSchedules = document.getElementsByClassName("board-schedules")[0] as HTMLElement
    val dateView = document.getElementsByClassName("board-header-date")[0] as HTMLElement
    val referenceTime = boardSchedules.dataset["reference"]?.toLongOrNull() ?: 0L

    val scheduleList = mutableListOf<BoardSchedule>()

    for (bs in boardSchedules.getElementsByClassName("board-schedule").iterator()) {
        scheduleList += BoardSchedule(bs)
    }

    interval(1000) {
        val currentTime = Date.now().toLong()
        dateView.innerText = formatDateTime(currentTime)

        val now = referenceTime - currentTime / 1000
        scheduleList.forEach { it.updateTime(now) }
    }
}