/* Get durations, historic and real time for all routes
   map (line =>
   	           (bound =>
   	           		("duration" => duration
   	           		 "historicDuration" => historic duration
   	           		 "realTimeDuration" => real time duration))) */
func getRouteDurations(lineBounds map[string]map[string]bool) map[string]map[string]map[string]time.Duration {
	allLineStopPoints := selectdb.SelectMultipleLineStopPoints(lineBounds)
	adjacentStops := extractAdjacentStops(allLineStopPoints)

	currentEstimates, currentHistoricEstimates, currentRealTimeEstimates, _, delayCounts, _ := selectdb.SelectCurrentEstimates(adjacentStops)

	routeDurations := make(map[string]map[string]map[string]time.Duration)

	for line, lineDetails := range lineBounds {
		for bound, _ := range lineDetails {

			duration, historicDuration, realTimeDuration, err := getRouteDuration(line, bound, allLineStopPoints[line][bound],
				currentEstimates, currentHistoricEstimates, currentRealTimeEstimates, delayCounts)

			if err != nil {
				logger.GetLogger().Error("Failed to get route duartion for line %v (%v): %v", line, bound, err.Error())
				continue
			}

			_, exists := routeDurations[line]
			if !exists {
				routeDurations[line] = make(map[string]map[string]time.Duration)
			}
			routeDurations[line][bound] = map[string]time.Duration{
				"duration":         duration,
				"historicDuration": historicDuration,
				"realTimeDuration": realTimeDuration,
			}
		}
	}
	return routeDurations
}
func dbToDelayedRoutes(delayedRoutes []selectdb.DelayedRoute) []DelayedRoute {
	lineBounds := make(map[string]map[string]bool)

	/* Extract intermediate stops for each bus route */
	for _, delayedRoute := range delayedRoutes {
		_, exists := lineBounds[delayedRoute.Line]
		if !exists {
			lineBounds[delayedRoute.Line] = make(map[string]bool)
		}
		lineBounds[delayedRoute.Line][delayedRoute.Bound] = true
	}
	allLineStopPoints := selectdb.SelectMultipleLineStopPoints(lineBounds)
	allStopInfos := getStopInfos(allLineStopPoints)

	DelayedRoutes := make([]DelayedRoute, 0)

	for _, delayedRoute := range delayedRoutes {
		line := delayedRoute.Line
		bound := delayedRoute.Bound
		duration := time.Duration(delayedRoute.Estimate) * time.Second
		historicDuration := time.Duration(delayedRoute.HistoricEstimate) * time.Second
		realTimeDuration := time.Duration(delayedRoute.RealTimeEstimate) * time.Second
		tflDuration := time.Duration(delayedRoute.TflEstimate) * time.Second

		DelayedRoute := DelayedRoute{
			Line:              line,
			Bound:             bound,
			IntermediateStops: allStopInfos[line][bound],
			Duration:          int(duration.Minutes()),
			HistoricDuration:  int(historicDuration.Minutes()),
			RealTimeDuration:  int(realTimeDuration.Minutes()),
			TflDuration:       int(tflDuration.Minutes()),
		}
		DelayedRoutes = append(DelayedRoutes, DelayedRoute)
	}
	return DelayedRoutes
}