penguin/golifehk

@golifehk bot in Telegram

datasources/mtr/bus/query.go

raw ยท 1505 bytes

package bus

import (
	"strings"

	query "github.com/tgckpg/golifehk/query"
)

func Query(q query.QueryMessage) query.IQueryResult {

	lang := q.Lang

	var qBusStops *query.QueryObject
	var err error

	qr := QueryResult{Lang: lang}
	busStops, err := getBusStops()
	if err != nil {
		qr.Error = err
		goto qrReturn
	}

	if q.Text != "" {
		qBusStops, err = query.MatchKeys(strings.ToUpper(q.Text), busStops)
	} else if q.Location != nil {
		qBusStops, err = query.MatchNearest(*q.Location, busStops, 100, 3)
	}

	qBusStops.Message = &q

	if err != nil {
		qr.Error = err
		goto qrReturn
	}

	qr.Query = qBusStops
	if 0 < len(*qBusStops.Results) && 1 < len(*qBusStops.SearchTerms) {
		schedules, err := getSchedule(lang, qBusStops.Key)
		if err != nil {
			qr.Error = err
			goto qrReturn
		}

		if len(schedules.BusStops) == 0 {
			qr.Schedules = &map[*BusStop]*BusStopBuses{}
			goto qrReturn
		}

		matches := map[*BusStop]*BusStopBuses{}
		sMatches := map[*BusStop]*BusStopBuses{}
		for _, entry := range *qBusStops.Results {
			busStop := any(entry).(*BusStop)

			for _, busStopSch := range schedules.BusStops {
				if busStopSch.BusStopId == busStop.StationId {
					if busStop.RouteId != busStop.ReferenceId {
						sMatches[busStop] = &busStopSch
						continue
					}
					matches[busStop] = &busStopSch
					break
				}
			}
		}

		if len(matches) == 0 && 0 < len(sMatches) {
			matches = sMatches
		}

		qr.Schedules = &matches
	}

qrReturn:
	var iqr query.IQueryResult
	iqr = &qr
	return iqr
}