package com.marvinelsen.willow.ui.controllers

import com.marvinelsen.willow.Model
import com.marvinelsen.willow.config.Config
import com.marvinelsen.willow.ui.DictionaryEntryFx
import com.marvinelsen.willow.ui.cells.DictionaryEntryCellFactory
import javafx.beans.binding.Bindings
import javafx.fxml.FXML
import javafx.scene.control.Label
import javafx.scene.control.ListView
import javafx.scene.control.ProgressIndicator
import java.util.ResourceBundle

class SearchResultsController(private val model: Model, private val config: Config) {
    @FXML
    private lateinit var resources: ResourceBundle

    @FXML
    private lateinit var progressIndicatorEntries: ProgressIndicator

    @FXML
    @Suppress("UnusedPrivateProperty")
    private lateinit var labelNoEntriesFound: Label

    @FXML
    private lateinit var listViewSearchResults: ListView<DictionaryEntryFx>

    @FXML
    @Suppress("UnusedPrivateMember")
    private fun initialize() {
        listViewSearchResults.cellFactory = DictionaryEntryCellFactory(resources, config)
        listViewSearchResults.items = model.searchResults
        listViewSearchResults
            .disableProperty()
            .bind(Bindings.or(model.isSearching, Bindings.isEmpty(model.searchResults)))

        progressIndicatorEntries.visibleProperty().bind(model.isSearching)
        labelNoEntriesFound
            .visibleProperty()
            .bind(Bindings.and(Bindings.isEmpty(model.searchResults), Bindings.not(model.isSearching)))

        listViewSearchResults.selectionModel.selectedItemProperty().addListener { _, _, newValue: DictionaryEntryFx? ->
            if (newValue == null) {
                return@addListener
            }
            model.selectEntry(newValue)
        }
    }
}
