package de.kif.frontend.views.calendar

import de.kif.common.model.WorkGroup
import de.kif.frontend.launch
import de.kif.frontend.repository.WorkGroupRepository
import de.westermann.kwebview.View

class CalendarWorkGroup(
    private val calendar: Calendar,
    private val calendarEdit: CalendarEdit,
    workGroup: WorkGroup
) : View() {
    private var language by dataset.property("language")

    lateinit var workGroup: WorkGroup
        private set

    private fun load(workGroup: WorkGroup) {
        this.workGroup = workGroup

        html.textContent = workGroup.name

        language = workGroup.language.code

        style {
            if (workGroup.track?.color != null) {
                backgroundColor = workGroup.track.color.toString()
                color = workGroup.track.color.calcTextColor().toString()
            }
        }
    }

    init {
        load(workGroup)

        val references: MutableList<de.westermann.kobserve.event.EventListener<*>> = mutableListOf()

        references += WorkGroupRepository.onUpdate.reference {
            if (it == workGroup.id) {
                launch {
                    load(WorkGroupRepository.get(it)!!)
                }
            }
        }

        references += WorkGroupRepository.onDelete.reference {
            if (it == workGroup.id) {
                calendarEdit.workGroupList -= this
            }
        }

        onMouseDown {
            CalendarEntry.create(calendar, workGroup)
        }
    }
}
