package de.kif.frontend.views.table

import de.kif.frontend.iterator
import de.westermann.kwebview.components.InputView
import org.w3c.dom.HTMLFormElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLTableElement
import org.w3c.dom.get
import kotlin.browser.document

fun initTableLayout() {
    val form = document.getElementsByClassName("table-layout-search")[0] as HTMLFormElement
    form.onsubmit = { false }

    val table = document.getElementsByClassName("table-layout-table")[0] as HTMLTableElement

    val list = table.getElementsByTagName("tr").iterator().asSequence().filter {
        it.dataset["search"] != null
    }.map {
        when (it.dataset["edit"]) {
            "workgroup" -> WorkGroupTableLine(it)
            "room" -> RoomTableLine(it)
            else -> TableLine(it)
        }
    }.toList()

    val input = form.getElementsByTagName("input")[0] as HTMLInputElement
    val search = InputView.wrap(input)
    search.valueProperty.onChange {
        for (row in list) {
            row.search(search.value)
        }
    }
}
