ScheduleController::findAllNext

This commit is contained in:
Patrick Haßel 2021-10-03 22:09:57 +02:00
parent f67a0497cb
commit caa7e55d10

View File

@ -1,11 +1,16 @@
package de.ph87.homeautomation.schedule; package de.ph87.homeautomation.schedule;
import de.ph87.homeautomation.schedule.entry.ScheduleEntry;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; 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.List;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@RestController @RestController
@ -20,4 +25,37 @@ public class ScheduleController {
return scheduleRepository.findAll().stream().map(ScheduleDto::new).collect(Collectors.toList()); return scheduleRepository.findAll().stream().map(ScheduleDto::new).collect(Collectors.toList());
} }
@GetMapping("findAllNext")
public List<ScheduleEntryNextDto> 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<String, String> 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<ScheduleEntryNextDto> 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));
}
}
} }