package org.hso.texturesyncclient.view.mainView

import javafx.animation.Interpolator
import javafx.animation.RotateTransition
import javafx.geometry.Insets
import javafx.scene.AmbientLight
import javafx.scene.PointLight
import javafx.scene.image.Image
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.paint.Color
import javafx.scene.paint.PhongMaterial
import javafx.scene.shape.Box
import javafx.scene.transform.Rotate
import tornadofx.*

class Preview3D : View("Preview3D") {

    private val boxSize = 100.0
    private val dBox = Box(boxSize, boxSize, boxSize)
    private val rxBox = Rotate(45.0, 0.0, 0.0, 0.0, Rotate.X_AXIS)
    private val ryBox = Rotate(45.0, 0.0, 0.0, 0.0, Rotate.Y_AXIS)

    private val pointLightFront = PointLight(Color.WHITE)
    private val ambient = AmbientLight(Color.ANTIQUEWHITE)

    init {
        // add rotation to the box
        dBox.transforms.addAll(rxBox, ryBox)

        // light stuff
        pointLightFront.translateX = boxSize
        pointLightFront.translateY = boxSize
        pointLightFront.translateZ = (-2 * boxSize)
        pointLightFront.rotate = 90.0
    }

    override val root = stackpane {

        add(dBox).apply {
            // rotate the box from 0° to 360° for infinity around the y axis
            dBox.rotationAxis = Rotate.Y_AXIS
            timeline {
                keyframe(18.seconds) {
                    keyvalue(dBox.rotateProperty(), 360.0, interpolator = Interpolator.LINEAR)
                }
                cycleCount = RotateTransition.INDEFINITE
            }
        }

        add(pointLightFront)
        add(ambient)

        style {
            minWidth = 200.px
            minHeight = 200.px
            background = Background(BackgroundFill(Color.valueOf("#3a3a3a"), CornerRadii.EMPTY, Insets.EMPTY))
        }

    }

    /**
     * set the texture of the bock
     * @param img the texture to set
     */
    fun setTexture(img: Image) {
        val textureMaterial = PhongMaterial()
        textureMaterial.diffuseMap = img
        dBox.material = textureMaterial
    }

}
