package com.marvinelsen.willow.ui.controllers

import com.marvinelsen.willow.Model
import com.marvinelsen.willow.ui.DictionaryEntryFx
import javafx.beans.binding.Bindings
import javafx.fxml.FXML
import javafx.scene.control.Label
import javafx.scene.control.ListView
import javafx.scene.control.TabPane
import javafx.scene.web.WebView

class DetailsController(private val model: Model) {
    @FXML
    private lateinit var tabPaneDetails: TabPane

    @FXML
    private lateinit var webViewDefinition: WebView

    @FXML
    @Suppress("UnusedPrivateProperty")
    private lateinit var listviewSentences: ListView<DictionaryEntryFx>

    @FXML
    private lateinit var listViewWords: ListView<DictionaryEntryFx>

    @FXML
    @Suppress("UnusedPrivateProperty")
    private lateinit var listViewCharacters: ListView<DictionaryEntryFx>

    @FXML
    private lateinit var labelHeadword: Label

    @FXML
    @Suppress("UnusedPrivateMember")
    private fun initialize() {
        val headwordObjectBinding =
            Bindings.createStringBinding({ model.selectedEntry.value?.traditionalProperty?.value }, model.selectedEntry)

        labelHeadword.textProperty().bind(headwordObjectBinding)

        tabPaneDetails.disableProperty().bind(Bindings.isNull(model.selectedEntry))

        listViewWords.items = model.wordsContaining
        tabPaneDetails.selectionModel.selectedItemProperty().addListener { _, _, selectedTab ->
            if (model.selectedEntry.value == null) return@addListener

            when (selectedTab.id) {
                "tabWords" -> {
                    model.findWords()
                }

                else -> {}
            }
        }

        webViewDefinition.apply {
            isContextMenuEnabled = false
            engine.userStyleSheetLocation =
                this::class.java.getResource("/css/definitions.css")!!.toExternalForm()
        }

        model.selectedEntry.addListener { _, _, newValue ->
            if (newValue == null) {
                return@addListener
            }
            webViewDefinition.engine.loadContent(
                buildString {
                    append("<html>")
                    append("<body>")
                    append("<h1>CC-CEDICT</h1>")
                    append("<ol>")
                    for (definition in newValue.definitions) {
                        append("<li>")
                        append(definition.joinToString(separator = "; "))
                        append("</li>")
                    }
                    append("</ol>")
                    append("</body>")
                    append("</html>")
                }
            )
        }
    }
}
