package org.hso.texturesyncclient.view.importView

import javafx.scene.image.Image
import javafx.stage.FileChooser
import org.hso.texturesyncclient.controller.RootController
import tornadofx.Controller
import java.io.File
import java.io.FileInputStream


class ImportViewController : Controller() {

    private val iv = find(ImportView::class)
    private val rootc = find(RootController::class)

    private var lastImportDir: String = System.getProperty("user.home")

    fun btnFileChooserAction() {
        val fileChooser = FileChooser()
        val fileExtensions = FileChooser.ExtensionFilter(
            "Texturen vom Bildformat: PNG oder JPEG", "*.png", "*.PNG", "*.jpg", "*.JPG", "*.jpeg", "*.JPEG"
        )

        fileChooser.extensionFilters.addAll(fileExtensions)
        fileChooser.initialDirectory = File(lastImportDir)
        fileChooser.title = "Textur auswählen"

        val file = fileChooser.showOpenDialog(null)

        if (file != null) {
            iv.tfFilePath.text = file.absolutePath
            iv.tfName.text = file.nameWithoutExtension
            lastImportDir = file.parent.toString() //store last user chosen dir

            runAsync {
                try {
                    val fileInput = FileInputStream(file.absolutePath)
                    val img = Image(fileInput)
                    iv.preview.setTexture(img)
                    iv.preview.root.isVisible = true
                } catch (e: Exception) {
                    // Got a catch'em all
                    println(e.message)
                }
            }
        }
    }

    fun btnImportAction() {
        rootc.importTexture(iv.tfFilePath.text, iv.tfName.text, iv.cvTags.chips)
        RootController.switchImportToMain(true)
        reset()
    }

    fun validateImport() {
        iv.btnImport.isVisible =
            iv.tfFilePath.text.isNotEmpty() && iv.tfName.text.isNotEmpty() && iv.cvTags.chips.isNotEmpty() && iv.cvTags.chips.stream().allMatch { x -> x.length < 32 }
    }

    fun btnBackAction() {
        RootController.switchImportToMain(false)
        reset()
    }

    private fun reset() {
        iv.tfFilePath.clear()
        iv.tfName.clear()
        iv.cvTags.chips.clear()
        iv.preview.root.isVisible = false
    }
}
