package de.kif.frontend.views.overview

import de.kif.frontend.iterator
import de.kif.frontend.launch
import de.kif.frontend.repository.PostRepository
import de.westermann.kobserve.event.subscribe
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLTextAreaElement
import org.w3c.dom.events.EventListener
import org.w3c.dom.get
import org.w3c.files.File
import org.w3c.files.FileReader
import org.w3c.files.get
import kotlin.browser.document
import kotlin.dom.clear

private fun sortOverviewPosts(container: HTMLElement) {
    val list = container.children.iterator().asSequence().toList()

    val sorted = list.sortedWith(compareBy(
        { if (it.dataset["pinned"]?.toBoolean() == true) 0 else 1 },
        { -(it.dataset["id"]?.toLong() ?: -1) }
    ))

    container.clear()

    for (element in sorted) {
        container.appendChild(element)
    }
}

fun initOverviewMain() {
    val main = document.getElementsByClassName("overview-main")[0] as HTMLElement

    PostRepository.onCreate {
        val post = PostView.create(it)
        post.classList += "overview-post"
        main.appendChild(post.html)

        sortOverviewPosts(main)
    }

    subscribe<PostChangeEvent> {
        sortOverviewPosts(main)
    }
}

fun initPosts() {
    val postList = document.getElementsByClassName("post")
    for (post in postList) {
        PostView(post)
    }
}

fun initPostEdit() {
    // Content preview
    val textArea = document.getElementById("content") as HTMLTextAreaElement
    val preview = document.getElementsByClassName("post-edit-right")[0] as HTMLElement

    textArea.addEventListener("change", EventListener {
        launch {
            preview.innerHTML = PostRepository.render(textArea.value)
        }
    })
    textArea.addEventListener("keyup", EventListener {
        launch {
            preview.innerHTML = PostRepository.render(textArea.value)
        }
    })

    launch {
        preview.innerHTML = PostRepository.render(textArea.value)
    }

    // Image preview
    val imageView = document.getElementsByClassName("post-edit-image")[0] as HTMLElement
    val uploadButton = document.getElementById("image") as HTMLInputElement
    val deleteSwitch = document.getElementById("image-delete") as? HTMLInputElement

    var file: File? = null
    val original = imageView.style.backgroundImage

    fun updateImage() {
        val deleteState = deleteSwitch?.checked == true
        val f = file

        when {
            deleteState -> {
                imageView.removeAttribute("style")
                uploadButton.value  = ""
                file = null
            }
            f == null -> imageView.style.backgroundImage = original
            else -> {
                val reader = FileReader()
                reader.onload = {
                    val dataUrl = it.target.asDynamic().result as String
                    imageView.style.backgroundImage = "url(\"$dataUrl\")"
                    Unit
                }
                reader.readAsDataURL(f)
            }
        }
    }

    uploadButton.addEventListener("change", EventListener {
        val files = uploadButton.files ?: return@EventListener
        file = files[0]
        updateImage()
    })

    deleteSwitch?.addEventListener("change", EventListener {
        updateImage()
    })
}