blob: ae6c6f9f9190b2fafd029a817a7f012b41f12f37 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
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<ServerClient, String> onLoggedIn;
public void init(String server, String user, BiConsumer<ServerClient, String> 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<String> 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);
}
}
|