package application.controller

import application.model.*
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Button
import javafx.scene.control.Slider
import java.net.URL
import java.util.*


class TimePanel : Initializable {

    @FXML
    var timeSlider = Slider()

    @FXML
    var timeStop = Button()

    @FXML
    var timePlay = Button()


    override fun initialize(location: URL?, resources: ResourceBundle?) {
        setSliderMinMax()
        setSliderListener()
        disableAllButton()
        setDisable()
    }

    private fun setSliderMinMax() {
        timeSlider.min = 0.0
        timeSlider.max = 0.0
        observableVessel.listeners.add(object : MessageListener {
            override fun onValueChanged(newValue: MutableMap<String?, Vessel>) {
                timeSlider.max = Vessel.maxTime.toDouble()
                timeSlider.min = Vessel.minTime.toDouble()
            }
        })
    }

    private fun setSliderListener() {
        timeSlider.valueProperty().addListener { _, _, newValue ->
            observableCurrentTime.value = newValue.toInt()
        }
    }

    private fun disableAllButton() {
        timeStop.isDisable = true
        timeSlider.isDisable = true
        timePlay.isDisable = true
    }

    private fun unableAllButton() {
        timeStop.isDisable = false
        timeSlider.isDisable = false
        timePlay.isDisable = false
    }

    private fun setDisable() {
        observableIsReplayState.listeners.add(object : ReplayState {
            override fun onValueChanged(newValue: Boolean) {
                if (observableIsReplayState.value) {
                    observableCurrentTime.value = timeSlider.value.toInt()
                    unableAllButton()
                } else {
                    observableCurrentTime.value = Int.MAX_VALUE
                    disableAllButton()
                }
            }
        })
    }

}