carpool-service/helpers/regular_routes.go

79 lines
2.0 KiB
Go
Raw Normal View History

2023-03-29 10:50:25 +00:00
package helpers
2023-03-27 18:54:56 +00:00
import (
"errors"
"strconv"
"strings"
"time"
"github.com/paulmach/orb/geojson"
"github.com/rs/zerolog/log"
)
type PlannedRouteSchedule struct {
Route RegularRoute
DepartureDate time.Time
}
type RegularRoute geojson.FeatureCollection
func (rr RegularRoute) PlannedJourneySchedules(mindate time.Time, maxdate time.Time) ([]PlannedRouteSchedule, error) {
log.Debug().
Str("regular_route.id", rr.ExtraMembers.MustString("id", "")).
Str("mindate", mindate.Format(time.RFC3339)).
Str("maxdate", maxdate.Format(time.RFC3339)).
Msg("carpool service handler - PlannedJourneySchedules")
results := []PlannedRouteSchedule{}
current_date := mindate
for current_date.Before(maxdate) {
day := strings.ToUpper(current_date.Format("Mon"))
time_of_day, err := rr.checkSchedules(day)
if err != nil {
log.Error().
Err(err).
Str("day", day).
Msg("schedules not found")
}
if time_of_day != "" {
splitted := strings.Split(time_of_day, ":")
h, _ := strconv.Atoi(splitted[0])
m, _ := strconv.Atoi(splitted[1])
t := time.Date(current_date.Year(), current_date.Month(), current_date.Day(), h, m, 0, 0, time.Local)
results = append(results, PlannedRouteSchedule{
Route: rr,
DepartureDate: t,
})
}
current_date = current_date.Add(24 * time.Hour)
}
return results, nil
}
func (rr RegularRoute) checkSchedules(day string) (timeOfDay string, err error) {
if properties, ok := rr.ExtraMembers["properties"]; ok {
if propertiesMap, ok := properties.(map[string]any); ok {
if schedules, ok := propertiesMap["schedules"]; ok {
if schedulesSlice, ok := schedules.([]any); ok {
for _, sched := range schedulesSlice {
if daySchedule, ok := sched.(map[string]any); ok {
if daySchedule["day"].(string) == day {
return daySchedule["time_of_day"].(string), nil
}
}
}
}
}
}
}
return "", errors.New("not found")
}
func (rr RegularRoute) FeatureCollection() *geojson.FeatureCollection {
fc := geojson.FeatureCollection(rr)
return &fc
}