]> git.basschouten.com Git - openhab-addons.git/blob
1ee37c4ae4e2f43fa77e0da7f324b1ba1a969da8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.deutschebahn.internal.timetable;
14
15 import java.util.Comparator;
16 import java.util.Date;
17
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.binding.deutschebahn.internal.EventAttribute;
20 import org.openhab.binding.deutschebahn.internal.EventType;
21 import org.openhab.binding.deutschebahn.internal.timetable.dto.Event;
22 import org.openhab.binding.deutschebahn.internal.timetable.dto.TimetableStop;
23
24 /**
25  * {@link Comparator} that sorts the {@link TimetableStop} according planned date and time.
26  *
27  * @author Sönke Küper - initial contribution
28  */
29 @NonNullByDefault
30 public class TimetableStopComparator implements Comparator<TimetableStop> {
31
32     private final EventType eventSelection;
33
34     /**
35      * Creates a new {@link TimetableStopComparator} that sorts {@link TimetableStop} according the Event selected
36      * selected by the given {@link EventType}.
37      */
38     public TimetableStopComparator(EventType eventSelection) {
39         this.eventSelection = eventSelection;
40     }
41
42     @Override
43     public int compare(TimetableStop o1, TimetableStop o2) {
44         return determinePlannedDate(o1, this.eventSelection).compareTo(determinePlannedDate(o2, this.eventSelection));
45     }
46
47     /**
48      * Returns the planned-Time for the given {@link TimetableStop}.
49      * The time will be returned from the {@link Event} selected by the given {@link EventType}.
50      * If the {@link TimetableStop} has no according {@link Event} the other Event will be used.
51      */
52     private static Date determinePlannedDate(TimetableStop stop, EventType eventSelection) {
53         Event selectedEvent = eventSelection.getEvent(stop);
54         if (selectedEvent == null) {
55             selectedEvent = eventSelection.getOppositeEvent(stop);
56         }
57         if (selectedEvent == null) {
58             throw new AssertionError("one event is always present");
59         }
60         final Date value = EventAttribute.PT.getValue(selectedEvent);
61         if (value == null) {
62             throw new AssertionError("planned time cannot be null");
63         }
64         return value;
65     }
66 }