nquest/pkg/controller/engine.go

99 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-11-01 23:21:12 +03:00
package controller
import (
"errors"
2023-11-01 23:21:12 +03:00
"net/http"
"github.com/google/uuid"
2023-11-01 23:21:12 +03:00
"github.com/labstack/echo/v4"
2024-01-05 03:50:33 +03:00
"gitrepo.ru/neonxp/nquest/api"
2023-11-01 23:21:12 +03:00
"gitrepo.ru/neonxp/nquest/pkg/contextlib"
"gitrepo.ru/neonxp/nquest/pkg/models"
"gitrepo.ru/neonxp/nquest/pkg/service"
)
type Engine struct {
2024-01-05 03:50:33 +03:00
GameService *service.Game
EngineService *service.Engine
2023-11-01 23:21:12 +03:00
}
2024-01-05 03:50:33 +03:00
// (GET /engine/{uid})
func (ec *Engine) GameEngine(c echo.Context, uid uuid.UUID) error {
2023-11-01 23:21:12 +03:00
user := contextlib.GetUser(c)
2024-01-05 03:50:33 +03:00
game, err := ec.GameService.GetByID(c.Request().Context(), uid)
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
cursor, err := ec.EngineService.GetState(c.Request().Context(), game, user)
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
return c.JSON(http.StatusOK, mapCursorToTask(cursor, nil))
2024-01-05 03:50:33 +03:00
}
// (POST /engine/{uid}/code)
func (ec *Engine) EnterCode(c echo.Context, uid uuid.UUID) error {
2024-01-05 03:50:33 +03:00
user := contextlib.GetUser(c)
ctx := c.Request().Context()
game, err := ec.GameService.GetByID(ctx, uid)
2023-11-01 23:21:12 +03:00
if err != nil {
return err
}
2024-01-05 03:50:33 +03:00
req := &api.EnterCodeJSONRequestBody{}
if err := c.Bind(req); err != nil {
return err
}
cursor, err := ec.EngineService.EnterCode(ctx, game, user, req.Code)
message := api.OkCode
2023-11-01 23:21:12 +03:00
if err != nil {
switch {
case errors.Is(err, service.ErrGameFinished):
message = api.GameComplete
case errors.Is(err, service.ErrInvalidCode):
message = api.InvalidCode
case errors.Is(err, service.ErrOldCode):
message = api.OldCode
case errors.Is(err, service.ErrNextLevel):
message = api.NextLevel
default:
return c.JSON(http.StatusBadRequest, &api.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
})
}
2023-11-01 23:21:12 +03:00
}
return c.JSON(http.StatusOK, mapCursorToTask(cursor, &message))
2023-11-01 23:21:12 +03:00
}
func mapCursorToTask(cursor *models.GameCursor, message *api.TaskViewMessage) *api.TaskView {
2024-01-05 03:50:33 +03:00
resp := &api.TaskResponse{
Message: message,
Codes: make([]api.CodeView, 0, len(cursor.Task.Codes)),
// Solutions: []api.SolutionView{},
Text: cursor.Task.Text,
Title: cursor.Task.Title,
2024-01-05 03:50:33 +03:00
}
for _, code := range cursor.Task.Codes {
c := api.CodeView{
2024-04-29 23:31:44 +03:00
Description: &code.Description,
}
for _, cd := range cursor.Codes {
if cd.ID == code.ID {
c.Code = &cd.Code
break
}
}
resp.Codes = append(resp.Codes, c)
2024-01-05 03:50:33 +03:00
}
2024-01-05 03:50:33 +03:00
return resp
2023-11-01 23:21:12 +03:00
}