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

import be.iminds.ilabt.jfed.util.IOUtils;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;
import org.slf4j.LoggerFactory;

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

/**
 * StringArgumentChooser
 */
public class MultiLineStringArgumentChooser extends CommandArgumentChooser<String> implements Initializable {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(MultiLineStringArgumentChooser.class);

    @FXML
    private TextArea valueField;
    @FXML
    private Button loadFromFileButton;

    public MultiLineStringArgumentChooser(String defaultValue, boolean showLoadFromFileButton) {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MultiLineStringArgumentChooser.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
            if (defaultValue != null)
                valueField.setText(defaultValue);

            loadFromFileButton.setVisible(showLoadFromFileButton);

        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

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

    public void loadFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open File");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("All Files", "*.*"));
        File file = fileChooser.showOpenDialog(valueField.getScene().getWindow());
        if (file != null) {
            final String content;
            try {
                content = IOUtils.fileToString(file);
                Platform.runLater(() -> valueField.setText(content));
            } catch (IOException e) {
                LOG.error("Failed to open file: " + file.getPath(), e);
            }
        }
    }

    public void setValue(String v) {
        valueField.textProperty().set(v);
    }
}
