package be.iminds.ilabt.jfed.ui.javafx.probe_gui.command_arguments;

import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * StringArgumentChooser
 */
public class StringArgumentProvidedOptionsChooser extends CommandArgumentChooser<String> implements Initializable {
    @FXML
    private ComboBox<String> valueField;

    public StringArgumentProvidedOptionsChooser(ObservableList<String> options) {
        this(options, null, true);
    }

    /**
     * @param defaultValue the value to select. If null, selects the last value.
     */
    public StringArgumentProvidedOptionsChooser(ObservableList<String> options, String defaultValue, boolean limitToOptions) {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("StringArgumentProvidedOptionsChooser.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();

            assert valueField != null;
            valueField.setItems(options);

            valueField.setEditable(!limitToOptions);

            if (!valueField.getItems().isEmpty()) {
                if (defaultValue == null)
                    valueField.getSelectionModel().selectLast();
                else {
                    if (options.contains(defaultValue))
                        valueField.getSelectionModel().select(defaultValue);
                    else {
                        if (limitToOptions)
                            valueField.getSelectionModel().clearSelection();
                        else {
                            valueField.setPromptText(defaultValue);
                            valueField.getSelectionModel().clearSelection();
                        }
                    }
                }
            }
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        value = valueField.getSelectionModel().selectedItemProperty();
    }
}
