package de.kif.frontend.views.overview

import de.kif.common.formatDateTime
import de.kif.frontend.launch
import de.kif.frontend.repository.PostRepository
import de.westermann.kobserve.event.emit
import de.westermann.kwebview.View
import de.westermann.kwebview.components.Link
import de.westermann.kwebview.createHtmlView
import org.w3c.dom.HTMLElement
import org.w3c.dom.get
import org.w3c.dom.set

class PostView(
    view: HTMLElement
) : View(view) {

    val postId = dataset["id"]?.toLongOrNull() ?: -1

    var pinned: Boolean
        get() = dataset["pinned"] == "true"
        set(value) {
            dataset["pinned"] = value.toString()
        }

    private val nameView: Link
    private val contentView: HTMLElement
    private val footerView: HTMLElement
    private val imageView: HTMLElement

    private fun reload() {
        launch {
            val p = PostRepository.get(postId) ?: return@launch

            classList["post-no-image"] = p.image == null

            nameView.text = p.name
            nameView.target = "/p/${p.url}"
            pinned = p.pinned

            if (p.image == null) {
                imageView.removeAttribute("style")
            } else {
                imageView.style.backgroundImage = "url(\"/images/${p.image}\")"
            }

            contentView.innerHTML = PostRepository.htmlByUrl(p.url)
            footerView.innerText = formatDateTime(p.createdAt)

            emit(PostChangeEvent(postId))
        }
    }

    init {
        nameView = Link.wrap(view.getByClassOrCreate("post-name"))

        val postColumn = view.getByClassOrCreate<HTMLElement>("post-column")
        val postColumnLeft = postColumn.getByClassOrCreate<HTMLElement>("post-column-left")
        val postColumnRight = postColumn.getByClassOrCreate<HTMLElement>("post-column-right")

        imageView = postColumnLeft.getByClassOrCreate("post-image", "figure")

        contentView = postColumnRight.getByClassOrCreate("post-content")
        footerView = postColumnRight.getByClassOrCreate("post-footer")

        PostRepository.onUpdate {
            if (it == postId) {
                reload()
            }
        }
        PostRepository.onDelete {
            html.remove()
        }
    }

    companion object {
        fun create(postId: Long): PostView {
            val div = createHtmlView<HTMLElement>()
            div.classList.add("post")
            div.dataset["id"] = postId.toString()
            return PostView(div).also(PostView::reload)
        }
    }
}

data class PostChangeEvent(val id: Long)

inline fun <reified T : HTMLElement> HTMLElement.getByClassOrCreate(name: String, newTagName: String? = null): T {
    val v = this.getElementsByClassName(name)[0] as? T

    if (v != null) {
        return v
    }

    val h = createHtmlView<T>(newTagName)
    h.classList.add(name)
    this.appendChild(h)
    return h
}