carpool-service/internal/regular-routes.go

82 lines
2.1 KiB
Go
Raw Normal View History

2023-03-30 06:44:58 +00:00
package internal
2023-03-27 18:54:56 +00:00
import (
"errors"
"strconv"
"strings"
"time"
"github.com/google/uuid"
2023-03-27 18:54:56 +00:00
"github.com/paulmach/orb/geojson"
"github.com/rs/zerolog/log"
)
type PlannedRouteSchedule struct {
ID string `bson:"_id"`
2023-03-27 18:54:56 +00:00
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{
ID: uuid.NewString(),
2023-03-27 18:54:56 +00:00
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
}