package de.kif.frontend.views.table

import de.kif.common.Search
import de.kif.common.SearchElement
import de.westermann.kwebview.View
import de.westermann.kwebview.components.ListView
import de.westermann.kwebview.components.TextView
import de.westermann.kwebview.components.textView
import org.w3c.dom.HTMLElement

open class TableLine(line: HTMLElement) : View(line) {

    open val searchElement: SearchElement = SearchElement.parse(dataset["search"]!!)

    fun search(value: String) {
        style.display = if (Search.match(value, searchElement)) "table-row" else "none"
    }

    protected fun setupEditable(view: TextView, regex: Regex = ".*".toRegex(), onSave: (String) -> Unit) {
        view.contentEditable = true

        view.onKeyDown {
            if (it.keyCode == 13) {
                it.preventDefault()

                view.blur()
                return@onKeyDown
            }
        }

        view.onKeyUp {
            view.classList["error"] = !regex.matches(view.text)
        }

        view.onBlur {
            view.classList["error"] = !regex.matches(view.text)
            if (!view.classList["error"]) {
                onSave(view.text)
            }
        }
    }

    protected fun setupBoolean(view: TextView, onSave: () -> Unit) {
        view.classList += "no-select"
        view.tabIndex = 0
        view.onClick {
            onSave()
        }
        view.onKeyDown {
            if (it.keyCode != 32) return@onKeyDown
            onSave()
        }
    }

    protected fun <T : Any> setupList(view: TextView, list: List<T?>, transform: (T) -> String, onSave: (T?) -> Unit) {
        view.classList += "no-select"
        view.tabIndex = 0

        val listView = ListView<TextView>()
        listView.classList += "table-select-box"

        for (elem in list) {
            val text = if (elem == null) "" else transform(elem)
            listView.textView(text) {
                onClick {
                    onSave(elem)
                    view.blur()
                }
            }
        }

        view.onFocus {
            view.html.appendChild(listView.html)
        }
        view.onBlur {
            listView.html.remove()
        }
    }
}
