From caa7e55d10996f13de884d7b7d4a230bdc0ad929 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patrick=20Ha=C3=9Fel?= Date: Sun, 3 Oct 2021 22:09:57 +0200 Subject: [PATCH] ScheduleController::findAllNext --- .../schedule/ScheduleController.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/main/java/de/ph87/homeautomation/schedule/ScheduleController.java b/src/main/java/de/ph87/homeautomation/schedule/ScheduleController.java index 68bb47d..be50d16 100644 --- a/src/main/java/de/ph87/homeautomation/schedule/ScheduleController.java +++ b/src/main/java/de/ph87/homeautomation/schedule/ScheduleController.java @@ -1,11 +1,16 @@ package de.ph87.homeautomation.schedule; +import de.ph87.homeautomation.schedule.entry.ScheduleEntry; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.time.ZonedDateTime; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; +import java.util.Optional; import java.util.stream.Collectors; @RestController @@ -20,4 +25,37 @@ public class ScheduleController { return scheduleRepository.findAll().stream().map(ScheduleDto::new).collect(Collectors.toList()); } + @GetMapping("findAllNext") + public List findAllNext() { + final ZonedDateTime now = ZonedDateTime.now(); + return scheduleRepository.findAll().stream() + .map(schedule -> ScheduleEntryNextDto.create(schedule, now)) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + } + + static class ScheduleEntryNextDto { + + public final String name; + + public final ZonedDateTime nextTimestamp; + + public final HashMap properties; + + private ScheduleEntryNextDto(final Schedule schedule, final ScheduleEntry entry) { + this.name = schedule.getName(); + this.nextTimestamp = entry.getNextDateTime(); + this.properties = new HashMap<>(entry.getProperties()); + } + + public static Optional create(final Schedule schedule, final ZonedDateTime now) { + return schedule.getEntries().stream() + .filter(entry -> entry.getNextDateTime() != null && entry.getNextDateTime().isAfter(now)) + .min(Comparator.comparing(ScheduleEntry::getNextDateTime)) + .map(scheduleEntry -> new ScheduleEntryNextDto(schedule, scheduleEntry)); + } + + } + }