package de.kif.frontend.views.table

import de.kif.common.SearchElement
import de.kif.frontend.iterator
import de.kif.frontend.launch
import de.kif.frontend.repository.RepositoryDelegate
import de.kif.frontend.repository.RoomRepository
import de.westermann.kwebview.components.TextView
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLSpanElement
import org.w3c.dom.get

class RoomTableLine(view: HTMLElement) : TableLine(view) {

    var lineId = dataset["id"]?.toLongOrNull() ?: -1

    private val room =
        RepositoryDelegate(RoomRepository, lineId)

    private val spanRoomName: TextView
    private val spanRoomPlaces: TextView
    private val spanRoomProjector: TextView

    override var searchElement: SearchElement = super.searchElement

    init {
        val spans = view.getElementsByTagName("span").iterator().asSequence().toList()

        spanRoomName =
            TextView.wrap(spans.first { it.dataset["editType"] == "room-name" } as HTMLSpanElement)
        spanRoomPlaces =
            TextView.wrap(spans.first { it.dataset["editType"] == "room-places" } as HTMLSpanElement)
        spanRoomProjector =
            TextView.wrap(spans.first { it.dataset["editType"] == "room-projector" } as HTMLSpanElement)

        setupEditable(spanRoomName) {
            launch {
                val wg = room.get()
                if (wg.name != it) {
                    RoomRepository.update(wg.copy(name = it))
                }
            }
        }

        setupEditable(spanRoomPlaces, "\\d+".toRegex()) {
            val number = it.toIntOrNull() ?: return@setupEditable
            launch {
                val wg = room.get()
                if (wg.places != number) {
                    RoomRepository.update(wg.copy(places = number))
                }
            }
        }

        setupBoolean(spanRoomProjector) {
            launch {
                val wg = room.get()
                RoomRepository.update(wg.copy(projector = !wg.projector))
            }
        }


        RoomRepository.onUpdate {
            if (it != lineId) return@onUpdate

            launch {
                val wg = RoomRepository.get(it) ?: return@launch
                room.set(wg)
                searchElement = wg.createSearch()

                spanRoomName.text = wg.name
                spanRoomPlaces.text = wg.places.toString()
                spanRoomProjector.text = wg.projector.toString()
            }
        }
    }
}