waituntil/src/main/java/de/jotoho/waituntil/TimeCalculator.java

80 lines
3 KiB
Java

package de.jotoho.waituntil;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.TimeZone;
import static java.lang.System.Logger.Level;
/*
waituntil - a tool for delaying command execution until the specified time
Copyright (C) 2023 Jonas Tobias Hopusch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* A utility class for calculating and announcing a target time based on user input.
*/
public final class TimeCalculator {
private static final String LANG_GERMAN = GlobalConf.langGerman;
/**
* Calculates and announces the target time based on the user input.
*
* @param userTimeInputRaw the user input representing the desired time
* @return the calculated target time as a {@link ZonedDateTime} object
*/
public static ZonedDateTime calculateAndAnnounceTargetTime(final String userTimeInputRaw) {
// Parsing user input to obtain the desired time
final var userTimeInputRelative = LocalTime.parse(userTimeInputRaw);
final var userTimeInputAbsolute = ZonedDateTime.of(
LocalDate.now(),
userTimeInputRelative,
TimeZone.getDefault().toZoneId()
);
// Adjusting the target time if it has already passed for the current day
final var userTimeInputFinal = (Instant.now().isBefore(userTimeInputAbsolute.toInstant()))
? userTimeInputAbsolute
: userTimeInputAbsolute.plusDays(1);
// Formatting the target time for display
final var formattedTimeStamp = userTimeInputFinal.format(
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
);
// Constructing the appropriate message based on the output language
final String formattedMessage;
switch (GlobalConf.applicationOutputLanguage) {
case LANG_GERMAN:
formattedMessage = ("Dieses Program wird bis zum %s warten.").formatted(formattedTimeStamp);
break;
default:
formattedMessage = "WaitUntil will suspend until %s".formatted(formattedTimeStamp);
break;
}
// Logging the message
System.getLogger("timecalculator").log(Level.INFO, formattedMessage);
return userTimeInputFinal;
}
}