package envoy.client.data; import java.io.IOException; import java.io.Serializable; import envoy.client.net.Client; import envoy.client.ui.list.ComponentListModel; import envoy.data.Message; import envoy.data.Message.MessageStatus; import envoy.data.User; import envoy.event.MessageStatusChangeEvent; /** * Represents a chat between two {@link User}s
* as a list of {@link Message} objects. *
* Project: envoy-client
* File: Chat.java
* Created: 19 Oct 2019
* * @author Maximilian Käfer * @author Leon Hofmeister * @author Kai S. K. Engelbart * @since Envoy v0.1-alpha */ public class Chat implements Serializable { private static final long serialVersionUID = -7751248474547242056L; private final User recipient; private final ComponentListModel model = new ComponentListModel<>(); /** * Provides the list of messages that the recipient receives.
* Saves the Messages in the corresponding chat at that Point. * * @param recipient the user who receives the messages * @since Envoy v0.1-alpha */ public Chat(User recipient) { this.recipient = recipient; } /** * Appends a message to the bottom of this chat * * @param message the message to append * @since Envoy v0.1-alpha */ public void appendMessage(Message message) { model.add(message); } /** * Sets the status of all chat messages received from the recipient to * {@code READ} starting from the bottom and stopping once a read message is * found. * * @param client the client instance used to notify the server about the message * status changes * @throws IOException if a {@link MessageStatusChangeEvent} could not be * delivered to the server * @since Envoy v0.3-alpha */ public void read(Client client) throws IOException { for (int i = model.size() - 1; i >= 0; --i) { final Message m = model.get(i); if (m.getSenderId() == recipient.getId()) { if (m.getStatus() == MessageStatus.READ) break; else { m.setStatus(MessageStatus.READ); // TODO: Cache events in offline mode client.sendEvent(new MessageStatusChangeEvent(m)); } } } } /** * @return {@code true} if the newest message received in the chat doesn't have * the status {@code READ} * @since Envoy v0.3-alpha */ public boolean isUnread() { return !model.isEmpty() && model.get(model.size() - 1).getStatus() != MessageStatus.READ; } /** * @return all messages in the current chat * @since Envoy v0.1-alpha */ public ComponentListModel getModel() { return model; } /** * @return the recipient of a message * @since Envoy v0.1-alpha */ public User getRecipient() { return recipient; } }