parcoursmob/utils/sorting/fleets.go

74 lines
2.1 KiB
Go
Executable File

package sorting
import (
"cmp"
"encoding/json"
"strings"
"git.coopgo.io/coopgo-platform/fleets/storage"
fleetsstorage "git.coopgo.io/coopgo-platform/fleets/storage"
"github.com/paulmach/orb/geo"
"github.com/paulmach/orb/geojson"
"github.com/rs/zerolog/log"
)
type VehiclesByLicencePlate []fleetsstorage.Vehicle
func (a VehiclesByLicencePlate) Len() int { return len(a) }
func (a VehiclesByLicencePlate) Less(i, j int) bool {
return strings.Compare(a[i].Data["licence_plate"].(string), a[j].Data["licence_plate"].(string)) < 0
}
func (a VehiclesByLicencePlate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
type BookingsByStartdate []fleetsstorage.Booking
func (a BookingsByStartdate) Len() int { return len(a) }
func (a BookingsByStartdate) Less(i, j int) bool {
return a[i].Startdate.Before(a[j].Startdate)
}
func (a BookingsByStartdate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
// Functions
func VehiclesByDistanceFrom(from geojson.Feature) func(vehicle1, vehicle2 storage.Vehicle) int {
return func(vehicle1, vehicle2 storage.Vehicle) int {
vehicle1Address, ok := vehicle1.Data["address"]
if !ok {
return 1
}
vehicle1Json, err := json.Marshal(vehicle1Address)
if err != nil {
log.Error().Err(err).Msg("failed marshalling vehicle 1 json")
return 1
}
vehicle1Geojson, err := geojson.UnmarshalFeature(vehicle1Json)
if err != nil {
log.Error().Err(err).Msg("failed unmarshalling vehicle 1 geojson")
return 1
}
vehicle2Address, ok := vehicle2.Data["address"]
if !ok {
log.Debug().Msg("Vehicle 2 does not have an address")
return -1
}
vehicle2Json, err := json.Marshal(vehicle2Address)
if err != nil {
log.Error().Err(err).Msg("failed marshalling vehicle 2 json")
return -1
}
vehicle2Geojson, err := geojson.UnmarshalFeature(vehicle2Json)
if err != nil {
log.Error().Err(err).Msg("failed unmarshalling vehicle 2 geojson")
return -1
}
distance1 := geo.Distance(from.Point(), vehicle1Geojson.Point())
distance2 := geo.Distance(from.Point(), vehicle2Geojson.Point())
return cmp.Compare(distance1, distance2)
}
}