carpool-service/internal/regular-routes.go

76 lines
2.2 KiB
Go

// package internal povides structs used internally within this carpool service
package internal
import (
"errors"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/paulmach/orb/geojson"
"github.com/rs/zerolog/log"
)
// RegularRoute is a utility struct to manipulate regular routes. It's just a GeoJSON feature collection with additional functions
type RegularRoute geojson.FeatureCollection
// PlannedRouteSchedules returns individual planned route schedules with 2 dates, from a regular schedule
func (rr RegularRoute) PlannedRouteSchedules(mindate time.Time, maxdate time.Time) ([]PlannedRouteSchedule, error) {
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)
if t.After(time.Now().Add(-1 * time.Hour)) {
results = append(results, PlannedRouteSchedule{
ID: uuid.NewString(),
Route: rr.FeatureCollection(),
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
}