aboutsummaryrefslogtreecommitdiff
path: root/pkg/view/settings.go
blob: bee3dc201b1f21d24ceb66ed7ae59df7cb95b491 (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
package view

import (
	"github.com/valyala/fasthttp"

	"git.sr.ht/~gabrielgio/img/pkg/database/repository"
	"git.sr.ht/~gabrielgio/img/pkg/ext"
	"git.sr.ht/~gabrielgio/img/templates"
)

type (
	SettingsView struct {
		// there is not need to create a controller for this
		settingsRepository repository.SettingsRepository
		userRepository     repository.UserRepository
	}
)

func NewSettingsView(
	settingsRespository repository.SettingsRepository,
	userRepository repository.UserRepository,
) *SettingsView {
	return &SettingsView{
		settingsRepository: settingsRespository,
		userRepository:     userRepository,
	}
}

func (self *SettingsView) Index(ctx *fasthttp.RequestCtx) error {
	s, err := self.settingsRepository.Load(ctx)
	if err != nil {
		return err
	}

	users, err := self.userRepository.List(ctx)
	if err != nil {
		return err
	}

	templates.WritePageTemplate(ctx, &templates.SettingsPage{
		Settings: s,
		Users:    users,
	})

	return nil
}

func (self *SettingsView) Save(ctx *fasthttp.RequestCtx) error {
	var (
		showMode  = string(ctx.FormValue("showMode")) == "on"
		showOwner = string(ctx.FormValue("showOwner")) == "on"
	)

	err := self.settingsRepository.Save(ctx, &repository.Settings{
		ShowMode:  showMode,
		ShowOwner: showOwner,
	})
	if err != nil {
		return err
	}

	return self.Index(ctx)
}

func (self *SettingsView) SetMyselfIn(r *ext.Router) {
	r.GET("/settings/", self.Index)
	r.POST("/settings/", self.Save)
}