package de.kif.frontend.views.calendar

import de.kif.common.Search
import de.kif.frontend.launch
import de.kif.frontend.repository.WorkGroupRepository
import de.westermann.kobserve.list.filterObservable
import de.westermann.kobserve.list.observableListOf
import de.westermann.kobserve.list.sortObservable
import de.westermann.kwebview.View
import de.westermann.kwebview.components.Button
import de.westermann.kwebview.components.InputView
import de.westermann.kwebview.components.ListView
import de.westermann.kwebview.extra.listFactory
import org.w3c.dom.HTMLButtonElement
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import kotlin.browser.document

class CalendarEdit(
    private val calendar: Calendar, view: HTMLElement
) : View(view) {

    private val toggleEditButton =
        Button.wrap(document.getElementById("calendar-edit-button") as HTMLButtonElement)

    val search =
        InputView.wrap(view.querySelector(".calendar-edit-search input") as HTMLInputElement)

    val listView = ListView.wrap<CalendarWorkGroup>(
        view.querySelector(".calendar-edit-list") as HTMLElement
    )

    private var loaded = false

    val workGroupList = observableListOf<CalendarWorkGroup>()
    private val sortedList = workGroupList.sortObservable(compareBy {
        it.workGroup.name
    }).filterObservable(search.valueProperty) { entry, search ->
        val s = entry.workGroup.createSearch()
        Search.match(search, s)
    }

    private fun load() {
        if (loaded) return
        loaded = true

        launch {
            for (workGroup in WorkGroupRepository.all()) {
                workGroupList += CalendarWorkGroup(calendar, this, workGroup)
            }
        }
    }

    init {
        toggleEditButton.onClick {
            calendar.classList.toggle("edit")

            if (!loaded) {
                load()
            }
        }

        WorkGroupRepository.onCreate {
            if (loaded) {
                launch {
                    workGroupList += CalendarWorkGroup(
                        calendar,
                        this,
                        WorkGroupRepository.get(it)!!
                    )
                }
            }
        }

        listView.listFactory(sortedList)
    }
}