package routes

//go:generate retool do go run convertjson.go

import (
	"encoding/json"
	"log"
	"path"
)

const assetDir = "data" // relative to this file

type svc struct {
	Svc    string  `json:"svc"`
	Routes []route `json:"routes"`
}

func (s *svc) dedupe() {
	routeset := make(map[route]struct{})
	deduped := make([]route, 0)
	for _, r := range s.Routes {
		if _, ok := routeset[r]; !ok {
			deduped = append(deduped, r)
		}
		routeset[r] = struct{}{}
	}
	s.Routes = deduped
}

func (s *svc) load(assetpath string) {
	bytes, err := Asset(assetpath)
	if err != nil {
		log.Fatalf("routes load err=%q", err)
	}
	json.Unmarshal(bytes, s)
	s.dedupe()
}

type route struct {
	Pattern string `json:"pattern"`
	Name    string `json:"name"`
	Method  string `json:"method"`
}

func (rm RouteMap) addRoutes(routes []route) {
	for _, r := range routes {
		var err error
		if r.Method == "" {
			err = rm.AddRouteAllMethods(r.Pattern, r.Name)
		} else {
			err = rm.AddRoute(r.Pattern, r.Method, r.Name)
		}
		if err != nil {
			log.Fatalf("add route err=%q", err)
		}
	}
}

var Routes map[string]RouteMap = make(map[string]RouteMap)

func init() {
	assets, err := AssetDir(assetDir)
	if err != nil {
		log.Println("warning: unable to find any route data")
		return
	}
	for _, a := range assets {
		s := &svc{}
		s.load(path.Join(assetDir, a))

		rm, ok := Routes[s.Svc]
		if !ok {
			rm = NewRouteMap()
			Routes[s.Svc] = rm
		}
		rm.addRoutes(s.Routes)
	}
}
