-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelloModel.java
More file actions
109 lines (87 loc) · 2.9 KB
/
HelloModel.java
File metadata and controls
109 lines (87 loc) · 2.9 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package com.example;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.function.Consumer;
import static com.example.FxUtils.runOnFx;
/**
* Model layer for the chatapp RuneChat.
* <p>
* Manages messages, the current topic, and sending/receiving messages via NtfyConnection.
*/
public class HelloModel {
private final NtfyConnection connection;
private final ObservableList<NtfyMessageDto> messages = FXCollections.observableArrayList();
private final StringProperty messageToSend = new SimpleStringProperty();
private final StringProperty currentTopic = new SimpleStringProperty();
public HelloModel(NtfyConnection connection) {
this.connection = connection;
this.currentTopic.set(connection.getCurrentTopic());
receiveMessage();
}
public ObservableList<NtfyMessageDto> getMessages() {
return messages;
}
public String getMessageToSend() {
return messageToSend.get();
}
public StringProperty messageToSendProperty() {
return messageToSend;
}
public void setMessageToSend(String message) {
messageToSend.set(message);
}
public String getCurrentTopic() {
return currentTopic.get();
}
public StringProperty currentTopicProperty() {
return currentTopic;
}
public void setCurrentTopic(String topic) {
if (topic != null && !topic.isBlank()) {
connection.setCurrentTopic(topic);
this.currentTopic.set(topic);
messages.clear();
receiveMessage();
}
}
public String getUserId() {
return connection.getUserId();
}
public String getGreeting() {
return "RuneChat";
}
public boolean canSendMessage() {
String msg = messageToSend.get();
return msg != null && !msg.isBlank();
}
public void sendMessageAsync(Consumer<Boolean> callback) {
String msg = messageToSend.get();
if (msg == null || msg.isBlank()) {
System.out.println("Nothing to send!");
callback.accept(false);
return;
}
connection.send(msg, success -> {
if (success) {
runOnFx(() -> {
if (msg.equals(messageToSend.get())) {
messageToSend.set("");
}
});
callback.accept(true);
} else {
System.out.println("Failed to send message!");
callback.accept(false);
}
});
}
public void receiveMessage() {
connection.receive(m -> {
if (m == null || m.message() == null || m.message().isBlank()) return;
runOnFx(() -> messages.add(m));
});
}
}