package com.marvinelsen.willow.ui.dialogs

import com.marvinelsen.willow.config.Config
import com.marvinelsen.willow.ui.controllers.dialogs.PreferencesDialogController
import javafx.fxml.FXMLLoader
import javafx.scene.control.ButtonType
import javafx.scene.control.Dialog
import javafx.scene.control.DialogPane
import javafx.stage.Modality
import javafx.stage.Stage
import javafx.stage.Window
import javafx.util.Callback
import java.util.ResourceBundle

class PreferencesDialog(
    owner: Window?,
    config: Config,
    resources: ResourceBundle,
) : Dialog<PreferencesDialog.Result>() {
    companion object {
        private const val MIN_HEIGHT = 400.0
        private const val MIN_WIDTH = 400.0
    }

    enum class Result {
        SAVE_CHANGES, DO_NOT_SAVE_CHANGES
    }

    init {
        val fxmlLoader = FXMLLoader()
        fxmlLoader.resources = resources
        fxmlLoader.controllerFactory = Callback { type ->
            when (type) {
                PreferencesDialogController::class.java -> PreferencesDialogController(config)
                else -> error("Trying to instantiate unknown controller type $type")
            }
        }

        val root = fxmlLoader.load(javaClass.getResourceAsStream("/fxml/dialogs/preferences.fxml")) as DialogPane
        root.prefHeightProperty().bind(dialogPane.scene.heightProperty())
        root.prefWidthProperty().bind(dialogPane.scene.widthProperty())

        dialogPane = root
        title = "Settings"
        isResizable = true

        initOwner(owner)
        initModality(Modality.APPLICATION_MODAL)

        (dialogPane.scene.window as Stage).apply {
            minWidth = MIN_WIDTH
            minHeight = MIN_HEIGHT
        }

        resultConverter = Callback(::convertToResult)
    }

    private fun convertToResult(buttonType: ButtonType) =
        when (buttonType) {
            ButtonType.APPLY -> Result.SAVE_CHANGES
            else -> Result.DO_NOT_SAVE_CHANGES
        }
}
