package market.guess.ui.client; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import market.guess.api.Result; public final class LoginController { @FXML private TextField serverField; @FXML private TextField userField; @FXML private Label errorLabel; @FXML private Button loginBtn; private BiConsumer onLoggedIn; public void init(String server, String user, BiConsumer onLoggedIn) { serverField.setText(server); userField.setText(user); this.onLoggedIn = onLoggedIn; Platform.runLater(userField::requestFocus); } @FXML private void handleLogin() { var server = serverField.getText().trim().replaceAll("/+$", ""); var user = userField.getText(); loginBtn.setDisable(true); showError(null); CompletableFuture.supplyAsync(() -> connect(server, user)) .thenAcceptAsync( attempt -> { loginBtn.setDisable(false); if (attempt.result().isSuccess()) { onLoggedIn.accept(attempt.client(), attempt.result().getData()); } else { showError(attempt.result().getMessage()); } }, Platform::runLater); } private record Attempt(ServerClient client, Result result) {} private static Attempt connect(String server, String user) { ServerClient client; try { client = new ServerClient(server + "/api"); } catch (IllegalArgumentException e) { return new Attempt(null, Result.error("That is not a server address.")); } var result = client.login(user); if (result.isSuccess()) { client.pull(); } else { client.close(); } return new Attempt(client, result); } private void showError(String message) { errorLabel.setText(message); errorLabel.setVisible(message != null); errorLabel.setManaged(message != null); } }