package digital.willers.gui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;

import java.awt.*;
import java.io.File;
import java.io.IOException;

public class GUIController {
    private File selectedFile = null;

    @FXML
    private Button selectButton;

    @FXML
    private Button openButton;

    @FXML
    private TextField inputField;

    @FXML
    protected void selectFile(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Select your application");
        File file = fileChooser.showOpenDialog(null);
        if(file != null){
            System.out.println("File: " + file);
            inputField.setText(file.getAbsolutePath());
            this.selectedFile = file;
        }
    }

    @FXML
    protected void openFile(ActionEvent event) {
        if (inputField.getText().compareTo("") == 0) {
            System.out.println("Selected File is NULL");
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("Path not found");
            alert.setHeaderText("The path of the application could not be found");
            alert.setContentText("Please specify a valid path. With the 'Select' button you can choose the path of the application directly.");
            alert.showAndWait();
            return;
        }
        System.out.println("Open File");
        try {
            System.out.println("Try Open File");
            File file = new File(inputField.getText());
            Desktop.getDesktop().open(file);
        } catch (IOException e) {
            System.out.println("OPEN FAILED");
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("Application can not be called");
            alert.setHeaderText("The application could not be started");
            alert.setContentText("Unfortunately, something went wrong during the launch. Please check if you have selected the correct file to start the application.");
            alert.showAndWait();
            e.printStackTrace();
        }
        selectedFile = null;
    }
}
