Adds support for randomly selecting a time interval entry #11

This commit is contained in:
Kristian Knarvik 2022-10-15 11:30:53 +02:00
parent 0357de1cf7
commit dbdb38d158

View File

@ -6,6 +6,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random;
import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholder; import static net.knarcraft.blacksmith.formatting.StringFormatter.replacePlaceholder;
@ -46,19 +47,38 @@ public final class TimeFormatter {
List<TimeInterval> intervals = Arrays.stream(TimeInterval.values()).sorted().toList(); List<TimeInterval> intervals = Arrays.stream(TimeInterval.values()).sorted().toList();
for (TimeInterval interval : intervals) { for (TimeInterval interval : intervals) {
if (seconds < interval.getIntervalMax()) { if (seconds < interval.getIntervalMax()) {
//Use the set message, or use the default return getMessageFromInterval(interval);
//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 TimeInterval.INTERVAL_MORE_THAN_5_MINUTES.getDefaultText(); return TimeInterval.INTERVAL_MORE_THAN_5_MINUTES.getDefaultText();
} }
/**
* Gets the text string corresponding to the given time interval
*
* @param interval <p>The time interval to get text for</p>
* @return <p>Text describing the time interval</p>
*/
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 * Gets the string used for displaying this sign's duration
* *