package org.hso.texturesyncclient.view.mainView

import javafx.collections.ObservableList
import javafx.scene.image.Image
import org.hso.texturesyncclient.model.GUIModel
import tornadofx.Controller
import org.hso.texturesyncclient.controller.RootController
import org.hso.texturesyncclient.model.Texture

class MainViewController : Controller() {

    private val mv = find(MainView::class)
    private val rootc = find(RootController::class)

    // FolderView elements
    private val folderView = mv.folderView.root

    // DetailView elements
    private val preview = mv.detailView.preview
    private val metaLabel = mv.detailView.metaLabel
    private val cvTags = mv.detailView.cvTags

    // FolderView functions
    fun addElement(element: GUIModel) {
        folderView.children.add(element)
    }

    fun addAllElements(elementList: ArrayList<GUIModel>) {
        elementList.get(0).data
        folderView.children.addAll(elementList)
    }


    // DetailView functions
    fun setPreview3DTexture(img: Image) {
        preview.setTexture(img)
    }

    fun setMeta(name: String, res: String, etc: String) {
        metaLabel.text = "Name: $name\nAuflösung: $res\nAnderes: $etc"
    }

    fun setTags(chips: ObservableList<String>) {
        cvTags.chips.clear()
        cvTags.chips.addAll(chips)
    }

    fun updateTags() {
        println(cvTags.chips)
    }

    // DetailView actions

    fun cvSearchAction(tags: ObservableList<String>) {
        var previewList = arrayListOf<GUIModel>()

        // show spinner, block ui
        folderView.children.clear()
        mv.spinnerSearch.isVisible = true
        mv.cvSearch.isDisable = true

        runAsync {
            previewList = rootc.search(tags)
        } ui {
            // when search finished
            addAllElements(previewList)
            mv.spinnerSearch.isVisible = false
            mv.cvSearch.isDisable = false
        }


    }

    fun btnImportAction() {
        rootc.switchMainToImport()
    }


    fun removeTextureFromView(data: Texture) {
        // stream all children nodes, filter them as GUIModel with data.id == data.id, for any found object if it's still present remove it from the folderView
        folderView.children.stream().filter { x -> (x as GUIModel).data.id == data.id }.findAny().ifPresent{ x -> folderView.children.remove(x)}
    }


}