package api import ( "fmt" "net/http" "github.com/gin-gonic/gin" "git.nemunai.re/nemunaire/reveil/config" "git.nemunai.re/nemunaire/reveil/model" ) func declareRoutinesRoutes(cfg *config.Config, router *gin.RouterGroup) { router.GET("/routines", func(c *gin.Context) { routines, err := reveil.LoadRoutines(cfg) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()}) return } c.JSON(http.StatusOK, routines) }) router.POST("/routines", func(c *gin.Context) { c.AbortWithStatusJSON(http.StatusNotImplemented, gin.H{"errmsg": "TODO"}) }) routinesRoutes := router.Group("/routines/:tid") routinesRoutes.Use(func(c *gin.Context) { routines, err := reveil.LoadRoutines(cfg) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": err.Error()}) return } for _, t := range routines { if t.Id.ToString() == c.Param("tid") { c.Set("routine", t) c.Next() return } } c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"errmsg": "Routine not found"}) }) routinesRoutes.GET("", func(c *gin.Context) { c.JSON(http.StatusOK, c.MustGet("routine")) }) routinesRoutes.PUT("", func(c *gin.Context) { oldroutine := c.MustGet("routine").(*reveil.Routine) var routine reveil.Routine if err := c.ShouldBindJSON(&routine); err != nil { c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"errmsg": err.Error()}) return } if routine.Name != oldroutine.Name { err := oldroutine.Rename(routine.Name) if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to rename the routine: %s", err.Error())}) return } } // TODO: change actions c.JSON(http.StatusOK, oldroutine) }) routinesRoutes.DELETE("", func(c *gin.Context) { routine := c.MustGet("routine").(*reveil.Routine) err := routine.Remove() if err != nil { c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": fmt.Sprintf("Unable to remove the routine: %s", err.Error())}) return } c.JSON(http.StatusOK, nil) }) routinesRoutes.POST("/run", func(c *gin.Context) { routine := c.MustGet("routine").(*reveil.Routine) go routine.Launch(cfg) c.JSON(http.StatusOK, true) }) }