aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_search.go
blob: 3367a52299fa01468b72523a079b4d5a71fbf90e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package admin

import (
	"net/http"
	"strconv"
	"strings"
)

func (s *AdminServer) handleSearch(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	q := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("q")))
	if q == "" {
		writeJSON(w, map[string]any{"error": "missing query parameter 'q'"})
		return
	}

	type searchResult struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	}

	type searchResponse struct {
		Rooms   []searchResult `json:"rooms"`
		Items   []searchResult `json:"items"`
		Mobs    []searchResult `json:"mobs"`
		Objects []searchResult `json:"objects"`
		Hazards []searchResult `json:"hazards"`
	}

	var resp searchResponse

	roomIDs, _ := listYAMLFiles(s.dataDir, "rooms")
	for _, idStr := range roomIDs {
		roomID, err := strconv.Atoi(idStr)
		if err != nil {
			continue
		}
		room, err := s.world.LoadRoom(roomID)
		if err != nil {
			continue
		}
		if strings.Contains(strings.ToLower(room.Name), q) || strings.Contains(strings.ToLower(idStr), q) {
			resp.Rooms = append(resp.Rooms, searchResult{ID: idStr, Name: room.Name})
		}
	}

	for id := range s.itemStore.PathIndex() {
		itemDef, err := s.itemStore.Load(id)
		if err != nil {
			continue
		}
		if strings.Contains(strings.ToLower(itemDef.Name), q) || strings.Contains(strings.ToLower(itemDef.ID), q) {
			resp.Items = append(resp.Items, searchResult{ID: itemDef.ID, Name: itemDef.Name})
		}
	}

	mobIDs, _ := listYAMLFiles(s.dataDir, "mobs")
	for _, id := range mobIDs {
		mobDef, err := s.mobStore.LoadDef(id)
		if err != nil {
			continue
		}
		if strings.Contains(strings.ToLower(mobDef.Name), q) || strings.Contains(strings.ToLower(mobDef.ID), q) {
			resp.Mobs = append(resp.Mobs, searchResult{ID: mobDef.ID, Name: mobDef.Name})
		}
	}

	for id := range s.objectStore.PathIndex() {
		objDef, err := s.objectStore.Load(id)
		if err != nil {
			continue
		}
		if strings.Contains(strings.ToLower(objDef.Name), q) || strings.Contains(strings.ToLower(objDef.ID), q) {
			resp.Objects = append(resp.Objects, searchResult{ID: objDef.ID, Name: objDef.Name})
		}
	}

	hazardIDs, _ := listYAMLFiles(s.dataDir, "hazards")
	for _, id := range hazardIDs {
		h, err := s.world.LoadHazard(id)
		if err != nil {
			continue
		}
		if strings.Contains(strings.ToLower(h.Name), q) || strings.Contains(strings.ToLower(id), q) {
			resp.Hazards = append(resp.Hazards, searchResult{ID: id, Name: h.Name})
		}
	}

	writeJSON(w, resp)
}