|
| 1 | +package pro.cloudnode.smp.cloudnodemsg.message; |
| 2 | + |
| 3 | +import net.kyori.adventure.text.Component; |
| 4 | +import org.bukkit.OfflinePlayer; |
| 5 | +import org.bukkit.command.CommandSender; |
| 6 | +import org.bukkit.entity.Player; |
| 7 | +import org.jetbrains.annotations.NotNull; |
| 8 | +import pro.cloudnode.smp.cloudnodemsg.CloudnodeMSG; |
| 9 | +import pro.cloudnode.smp.cloudnodemsg.error.InvalidPlayerError; |
| 10 | + |
| 11 | +import java.util.Objects; |
| 12 | +import java.util.Optional; |
| 13 | +import java.util.UUID; |
| 14 | + |
| 15 | +public class Message { |
| 16 | + public final @NotNull OfflinePlayer sender; |
| 17 | + public final @NotNull OfflinePlayer recipient; |
| 18 | + public final @NotNull String message; |
| 19 | + |
| 20 | + public Message(final @NotNull OfflinePlayer sender, final @NotNull OfflinePlayer recipient, final @NotNull String message) { |
| 21 | + this.sender = sender; |
| 22 | + this.recipient = recipient; |
| 23 | + this.message = message; |
| 24 | + } |
| 25 | + |
| 26 | + private @NotNull String playerOrServerUsername(final @NotNull OfflinePlayer player) throws InvalidPlayerError { |
| 27 | + if (player.getUniqueId().equals(console.getUniqueId())) return CloudnodeMSG.getInstance().config().consoleName(); |
| 28 | + else { |
| 29 | + final @NotNull Optional<@NotNull String> name = Optional.ofNullable(player.getName()); |
| 30 | + if (name.isEmpty()) throw new InvalidPlayerError(); |
| 31 | + else return name.get(); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public void send() throws InvalidPlayerError { |
| 36 | + final @NotNull String senderUsername = playerOrServerUsername(this.sender); |
| 37 | + final @NotNull String recipientUsername = playerOrServerUsername(this.recipient); |
| 38 | + |
| 39 | + sendMessage(sender, CloudnodeMSG.getInstance().config().outgoing(senderUsername, recipientUsername, message)); |
| 40 | + sendMessage(recipient, CloudnodeMSG.getInstance().config().incoming(senderUsername, recipientUsername, message)); |
| 41 | + } |
| 42 | + |
| 43 | + public final static @NotNull OfflinePlayer console = CloudnodeMSG.getInstance().getServer() |
| 44 | + .getOfflinePlayer(UUID.fromString("00000000-0000-0000-0000-000000000000")); |
| 45 | + |
| 46 | + public static @NotNull OfflinePlayer offlinePlayer(final @NotNull CommandSender executor) { |
| 47 | + return executor instanceof final @NotNull Player player ? player : console; |
| 48 | + } |
| 49 | + |
| 50 | + public static void sendMessage(final @NotNull OfflinePlayer recipient, final @NotNull Component message) { |
| 51 | + if (recipient.getUniqueId() == console.getUniqueId()) CloudnodeMSG.getInstance().getServer().getConsoleSender().sendMessage(message); |
| 52 | + else if (recipient.isOnline()) Objects.requireNonNull(recipient.getPlayer()).sendMessage(message); |
| 53 | + } |
| 54 | +} |
0 commit comments