package de.ph87.homeautomation.schedule.entry; import com.luckycatlabs.sunrisesunset.Zenith; import de.ph87.homeautomation.bulk.Bulk; import de.ph87.homeautomation.property.Property; import de.ph87.homeautomation.schedule.Schedule; import lombok.AccessLevel; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.time.ZonedDateTime; import java.util.Random; @Getter @Setter @Entity @NoArgsConstructor public class ScheduleEntry { private static final Random RANDOM = new Random(System.currentTimeMillis()); @Id @GeneratedValue @Setter(AccessLevel.NONE) private Long id; @ManyToOne private Schedule schedule; private int position; private boolean enabled = false; private boolean monday = true; private boolean tuesday = true; private boolean wednesday = true; private boolean thursday = true; private boolean friday = true; private boolean saturday = true; private boolean sunday = true; @Column(nullable = false) private ScheduleEntryType type = ScheduleEntryType.TIME; private double zenith = Zenith.CIVIL.degrees().doubleValue(); @Column(name = "hour_") private int hour = 0; @Column(name = "minute_") private int minute = 0; @Column(name = "second_") private int second = 0; private int fuzzySeconds = 0; @ManyToOne private Property property; @Column(name = "value_") private double value; @ManyToOne private Bulk bulk; private ZonedDateTime nextClearTimestamp; private ZonedDateTime lastClearTimestamp; @Setter(AccessLevel.NONE) private ZonedDateTime nextFuzzyTimestamp; public ScheduleEntry(final Schedule schedule) { this.schedule = schedule; this.position = schedule.getEntries().size(); } public void setNextClearTimestamp(final ZonedDateTime next) { nextClearTimestamp = next; if (nextClearTimestamp == null) { nextFuzzyTimestamp = null; } else { final int rangeFull = 2 * fuzzySeconds; final int fuzzySeconds = rangeFull > 0 ? RANDOM.nextInt(rangeFull) - this.fuzzySeconds : 0; nextFuzzyTimestamp = nextClearTimestamp.plusSeconds(fuzzySeconds); } } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append("(id="); builder.append(id); builder.append(", enabled="); builder.append(enabled); builder.append(", type="); builder.append(type); builder.append(", weekdays="); builder.append(monday ? "Mon" : "___"); builder.append(tuesday ? "Tue" : "___"); builder.append(wednesday ? "Wed" : "___"); builder.append(thursday ? "Thu" : "___"); builder.append(friday ? "Fri" : "___"); builder.append(saturday ? "Sat" : "___"); builder.append(sunday ? "Sun" : "___"); if (type != null) { switch (type) { case TIME: builder.append(", hour="); builder.append(hour); builder.append(", minute="); builder.append(minute); builder.append(", second="); builder.append(second); break; case SUNRISE: case SUNSET: builder.append(", zenith="); builder.append(zenith); break; } } builder.append(")"); return builder.toString(); } }