package de.kif.frontend.views.board

import com.soywiz.klock.DateFormat
import com.soywiz.klock.DateTimeTz
import com.soywiz.klock.KlockLocale
import com.soywiz.klock.locale.german
import de.kif.frontend.launch
import de.kif.frontend.repository.ScheduleRepository
import de.kif.frontend.views.overview.getByClassOrCreate
import de.westermann.kwebview.interval
import de.westermann.kwebview.iterator
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.get
import kotlin.browser.document
import kotlin.dom.clear
import kotlin.js.Date

fun initBoard() {
    val dateContainer = document.getElementsByClassName("board-header-date")[0] as HTMLElement

    val timeView = dateContainer.getByClassOrCreate<HTMLSpanElement>("board-header-date-time")
    val dateView = dateContainer.getByClassOrCreate<HTMLSpanElement>("board-header-date-date")

    val initTime = Date.now().toLong()
    val referenceInitTime = dateContainer.dataset["now"]?.toLongOrNull() ?: initTime
    val diff = initTime - referenceInitTime


    val boardRunning = document.getElementsByClassName("board-running")[0] as HTMLElement
    val scheduleList = mutableListOf<BoardSchedule>()
    val runningReferenceTime = boardRunning.dataset["reference"]?.toLongOrNull() ?: 0L

    fun update() {
        launch {
            scheduleList.clear()
            val list = ScheduleRepository.getUpcoming()
            boardRunning.clear()

            val now = Date.now().toLong() + diff

            for (s in list) {
                val v = BoardSchedule.create(s, runningReferenceTime, now)
                scheduleList += v
                boardRunning.appendChild(v.html)
            }
        }
    }

    for (bs in boardRunning.getElementsByClassName("board-schedule").iterator()) {
        scheduleList += BoardSchedule(bs).also {
            it.onRemove {
                update()
            }
        }
    }

    interval(1000) {
        val now = Date.now().toLong() + diff

        val dt = DateTimeTz.fromUnixLocal(now)

        timeView.textContent = DateFormat("HH:mm")
            .withLocale(KlockLocale.german)
            .format(dt)

        dateView.textContent = DateFormat("EEEE, d. MMMM y")
            .withLocale(KlockLocale.german)
            .format(dt)


        scheduleList.forEach { it.updateTime(now) }
    }

    ScheduleRepository.onCreate {
        update()
    }
    ScheduleRepository.onUpdate {
        update()
    }
    ScheduleRepository.onDelete {
        update()
    }
}
