From dbdb38d158f811996e1584b851b645503ea9bbdc Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Sat, 15 Oct 2022 11:30:53 +0200 Subject: [PATCH] Adds support for randomly selecting a time interval entry #11 --- .../blacksmith/formatting/TimeFormatter.java | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/src/main/java/net/knarcraft/blacksmith/formatting/TimeFormatter.java b/src/main/java/net/knarcraft/blacksmith/formatting/TimeFormatter.java index 6050cb3..59acf2f 100644 --- a/src/main/java/net/knarcraft/blacksmith/formatting/TimeFormatter.java +++ b/src/main/java/net/knarcraft/blacksmith/formatting/TimeFormatter.java @@ -6,6 +6,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Random; import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholder; @@ -46,19 +47,38 @@ public final class TimeFormatter { List intervals = Arrays.stream(TimeInterval.values()).sorted().toList(); for (TimeInterval interval : intervals) { if (seconds < interval.getIntervalMax()) { - //Use the set message, or use the default - //TODO: Check for commas in the message. If present, split on the comma and choose a random expression - String text = Translator.getTranslatedMessage(TranslatableMessage.valueOf(interval.name())); - if (text != null && !text.trim().isEmpty()) { - return text; - } else { - return interval.getDefaultText(); - } + return getMessageFromInterval(interval); } } return TimeInterval.INTERVAL_MORE_THAN_5_MINUTES.getDefaultText(); } + /** + * Gets the text string corresponding to the given time interval + * + * @param interval

The time interval to get text for

+ * @return

Text describing the time interval

+ */ + private static String getMessageFromInterval(TimeInterval interval) { + String text = Translator.getTranslatedMessage(TranslatableMessage.valueOf(interval.name())); + + //Choose a random entry if a comma-separated list is provided + if (text != null && text.contains(",")) { + String[] parts = text.split(","); + String randomPart = parts[new Random().nextInt(parts.length)]; + if (randomPart != null) { + text = randomPart; + } + } + + //Use the set message, or use the default + if (text != null && !text.trim().isEmpty()) { + return text; + } else { + return interval.getDefaultText(); + } + } + /** * Gets the string used for displaying this sign's duration *