aboutsummaryrefslogtreecommitdiff
path: root/modules/search/search.go
blob: 4048dbe7da94c47c80560a5074b915c8f2af5e15 (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
package search

import (
	"fmt"
	"log"
	"net/http"

	"fagott.pw/charakterin"
	"fagott.pw/grilist/grilist"
	"fagott.pw/grilist/modules/grils"

	"github.com/julienschmidt/httprouter"
)

type Module struct {
	g     *grilist.Grilist
	grils *grils.GrilsModule
}

type GrilResult struct {
	ID        int
	ImagePath string
	Name      string
}

func New() *Module {
	return &Module{}
}

func (m *Module) Name() string {
	return "Search"
}

func (m *Module) Init(g *grilist.Grilist) {
	m.g = g
	gm, ok := g.Modules["Grils"]
	if !ok {
		log.Fatal("search: grils module not found")
	}
	m.grils = gm.(*grils.GrilsModule)

	m.g.Router.GET("/search/gril_instant/*name", m.instantSearchGril)
}

func (m *Module) Interface() interface{} {
	return m
}

func (m *Module) ProvideDashboardData(user *charakterin.User) []grilist.DashboardCategory {
	return make([]grilist.DashboardCategory, 0)
}

func (m *Module) instantSearchGril(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	name := p.ByName("name")[1:]
	if len(name) < 2 {
		http.Error(w, "Bad Request", 400)
		return
	}

	rows, err := m.g.DB.Query(`SELECT id, name FROM grilist.search_grils($1)`, name)
	if err != nil {
		log.Println("error in instant gril search:", err)
		return
	}

	defer rows.Close()

	var results []GrilResult
	for rows.Next() {
		result := GrilResult{}
		if err := rows.Scan(&result.ID, &result.Name); err != nil {
			log.Println("error scanning in instant gril search", err)
			continue
		}

		// Jan: Das ist hier irgendwie scheisse, aber wir bauen ja grad irgendwie den kram auf Models um. Wir brauchen da
		// irgendwas besseres.
		result.ImagePath = fmt.Sprintf("http://img.grilist.moe/gril/thumb/%d.jpg", result.ID)
		results = append(results, result)
	}

	data := make(map[string]interface{})
	data["results"] = results
	m.g.Renderer.RenderPage("instant_search_results", w, data)
}