package de.ph87.homeautomation.schedule; import de.ph87.homeautomation.property.PropertyService; import de.ph87.homeautomation.property.PropertySetException; import de.ph87.homeautomation.schedule.entry.ScheduleEntry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.ZonedDateTime; import java.util.Comparator; @Slf4j @Service @Transactional @RequiredArgsConstructor public class ScheduleExecutionService { private final ScheduleReadService scheduleReadService; private final ScheduleCalculationService scheduleCalculationService; private final PropertyService propertyService; public void executeAllLastDue() { final ZonedDateTime now = ZonedDateTime.now(); scheduleReadService.findAll().forEach(schedule -> executeLastDue(schedule, now)); } private void executeLastDue(final Schedule schedule, final ZonedDateTime now) { schedule.getEntries().stream() .filter(entry -> entry.getNextFuzzyTimestamp() != null && !entry.getNextFuzzyTimestamp().isAfter(now)) .max(Comparator.comparing(ScheduleEntry::getNextFuzzyTimestamp)) .ifPresent(entry -> executeEntry(schedule, entry, now)); } private void executeEntry(final Schedule schedule, final ScheduleEntry entry, final ZonedDateTime now) { entry.setLastClearTimestamp(entry.getNextClearTimestamp()); log.info("Executing Schedule \"{}\" Entry {}", schedule.getName(), entry); try { propertyService.set(schedule.getPropertyName(), entry.getValue()); } catch (PropertySetException e) { log.error(e.getMessage()); } scheduleCalculationService.calculateSchedule(schedule, now); } }