1package controller
2
3import (
4 "net/http"
5 "strconv"
6 "time"
7
8 "git.sr.ht/~gabrielgio/midr/db"
9 "git.sr.ht/~gabrielgio/midr/worker"
10 "github.com/gin-gonic/gin"
11)
12
13type Env struct {
14 Entries db.EntryModel
15 Worker worker.Worker
16}
17
18func (e *Env) GetEntries(c *gin.Context) {
19 entries := e.Entries.All()
20 c.HTML(http.StatusOK, "index", entries)
21}
22
23func (e *Env) GetEntry(c *gin.Context) {
24 id := c.Param("id")
25 if id != "" {
26 entry := e.Entries.Find(id)
27 c.HTML(http.StatusOK, "entry", entry)
28 } else {
29 c.HTML(http.StatusOK, "entry", db.Entry{})
30 }
31}
32
33func (e *Env) UpdateEntry(c *gin.Context) {
34 var entry db.Entry
35 c.ShouldBind(&entry)
36 e.Entries.Update(entry)
37 c.Redirect(http.StatusFound, "/")
38}
39
40func (e *Env) CreateEntry(c *gin.Context) {
41 var entry db.Entry
42 c.ShouldBind(&entry)
43 e.Entries.Create(&entry)
44 e.Worker.SpawnWorker(&entry)
45 c.Redirect(http.StatusFound, "/")
46}
47
48func (e *Env) DeleteEntry(c *gin.Context) {
49 var entry db.Entry
50 id := c.Param("id")
51 e.Entries.Delete(id)
52 u64, _ := strconv.ParseUint(id, 10, 32)
53 e.Worker.RemoveJob(uint(u64))
54 c.HTML(http.StatusOK, "entry", entry)
55}
56
57func (e *Env) GetJobs(c *gin.Context) {
58 jobs := e.Worker.GetJobs()
59 c.JSON(http.StatusOK, jobs)
60}
61
62func (e *Env) StartScheduler() {
63 e.Worker.StartReader()
64 go func() {
65 for {
66 entries := e.Entries.All()
67
68 for _, entry := range entries {
69 e.Worker.SpawnWorker(&entry)
70 }
71 time.Sleep(30 * time.Second)
72 }
73 }()
74}