carpool-service/internal/regular-routes.go

76 lines
2.2 KiB
Go
Raw Normal View History

// package internal povides structs used internally within this carpool service
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"
)
// RegularRoute is a utility struct to manipulate regular routes. It's just a GeoJSON feature collection with additional functions
2023-03-27 18:54:56 +00:00
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) {
2023-03-27 18:54:56 +00:00
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,
})
}
2023-03-27 18:54:56 +00:00
}
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
}