summaryrefslogtreecommitdiff
path: root/pkg/api/guess.go
blob: 25d08d6a5f51c20c7ecb5ff45eb5798f973c23ac (plain) (blame)
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
package api

import (
	"time"

	"git.neonxp.ru/neonxp/guessr/pkg/middleware"
	"github.com/labstack/echo/v4"
)

func (h *Handler) PostGuess(c echo.Context) error {
	req := &postGuessRequest{}
	if err := c.Bind(req); err != nil {
		return err
	}

	if state := c.Get("state"); state == nil {
		return echo.ErrNotFound
	}

	state := c.Get("state").(*middleware.State)

	resp, err := h.places.Guess(
		c.Request().Context(),
		state.CurrentGUID, req.Lat, req.Lng)
	if err != nil {
		return err
	}

	addPoints := 1000 - resp.Distance
	if addPoints > 0 {
		state.Points += addPoints
	}
	state.CurrentGUID = ""
	state.Image = ""
	if err := middleware.SetState(c, *state, int(365*24*time.Hour)); err != nil {
		return err
	}

	return c.JSON(200, postGuessResponse{
		GUID:     resp.GUID,
		Image:    resp.Img,
		Name:     resp.Name,
		Geojson:  resp.Geojson,
		Distance: resp.Distance,
		State:    state,
	})
}

type postGuessRequest struct {
	Lat float32 `json:"lat"`
	Lng float32 `json:"lng"`
}

type postGuessResponse struct {
	GUID     string            `json:"guid"`
	Image    string            `json:"image"`
	Name     string            `json:"name"`
	Geojson  any               `json:"geojson"`
	Distance int               `json:"distance"`
	State    *middleware.State `json:"state"`
}