import javax.annotation.Nullable; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; /** * Custom implementation of {@link org.spongepowered.api.text.channel.MessageChannel MessageChannel} * * @param The targeted type to receive messages * @param The type of message to be sent to recipients */ public interface MessageChannel { /** * Sends a message to all recipients. * * @param message The message to be sent * * @implSpec The default implementation is to chain {@code send(null, message)} */ default void send(M message) { send(null, message); } /** * Sends a message to all recipients. * * @param sender The object which is sending the message * @param message The message to be sent * * @see MessageChannel#transformMessage(Object, R, M) */ default void send(@Nullable Object sender, M message) { Objects.requireNonNull(message, "message cannot be null"); getRecipients().forEach(recipient -> { transformMessage(sender, recipient, message).ifPresent(transformedMessage -> sendTo(recipient, transformedMessage)); }); } /** * Transforms a message with respect to a recipient. *

* {@code Optional.empty()} will be returned if the transformation decides this recipient should not receive the message *

* * @param sender The object which is sending the message * @param recipient The individual recipient who will be receiving the message * @param originalMessage The message to be transformed * * @return The transformed message */ default Optional transformMessage(@Nullable Object sender, R recipient, M originalMessage) { return Optional.of(originalMessage); } /** * Obtains a {@code Stream} of the channel recipients. *

* The recipients may change, so it is recommended to consume this Stream immediately. *

* * @return The current list of recipients */ Stream getRecipients(); /** * Sends an arbitrary message to an arbitrary recipient. *

* Mostly an implementation detail, as internally describes how to send a message to a recipient. *

* * @param recipient The recipient to send the message to * @param message The message to be sent */ void sendTo(R recipient, M message); }