package org.hso.texturesyncclient.model

import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.control.ContextMenu
import javafx.scene.control.Label
import javafx.scene.control.MenuItem
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.layout.VBox
import javafx.scene.paint.Paint
import tornadofx.addClass
import tornadofx.find
import tornadofx.paddingTop

class GUIModel constructor(var data: Texture, img: Image) : VBox() {

    private var image = ImageView()
    private var label = Label()
    private var contextMenu = ContextMenu()
    private var exportItem = MenuItem("exportiern")
    private var deleteItem = MenuItem("löschen")

    private lateinit var texture: Texture

    private val gmc = find(GUIModelController::class)

    init {
        texture = data
        super.setPadding(Insets(5.0, 5.0, 5.0, 5.0))
        super.getChildren().addAll(image, label)
        super.setOnContextMenuRequested { p0 -> contextMenu.show(this@GUIModel, p0.screenX, p0.screenY) }
        super.setOnMouseClicked {
            if (gmc.isLastSelectedInitialized()) {
                gmc.lastSelected.background = Background.EMPTY
                this.background = Background(BackgroundFill(Paint.valueOf("#2b7bbb"), CornerRadii.EMPTY, Insets.EMPTY))
                gmc.lastSelected = this
            } else {
                this.background = Background(BackgroundFill(Paint.valueOf("#2b7bbb"), CornerRadii.EMPTY, Insets.EMPTY))
                gmc.lastSelected = this
            }
            gmc.previewSelectedAction(data)
            gmc.setSelected(this)

        }

        label.addClass("metadata")
        label.paddingTop = 5.0
        label.prefWidth = 128.0
        label.alignment = Pos.CENTER

        label.text = if (data.name.length > 15) {
            "${data.name.subSequence(0, 14)}.."
        } else {
            data.name
        }

        label.background = Background(BackgroundFill(Paint.valueOf("#3a3a3a"), CornerRadii.EMPTY, Insets.EMPTY))

        image.fitHeight = 128.0
        image.fitWidth = 128.0
        image.image = img

        exportItem.setOnAction {
            gmc.export(data)
        }

        deleteItem.setOnAction {
            gmc.delete(data)
        }

        contextMenu.items.add(exportItem)
        contextMenu.items.add(deleteItem)
    }

    fun setTexture(data: Texture) {
        texture = data
    }

}