package server

import (
	"local/firestormy/config"
	"local/firestormy/config/ns"
	"local/firestormy/scheduler"
	"net/http"
	"strings"
)

func (s *Server) run(w http.ResponseWriter, r *http.Request) {
	keys := strings.Split(r.URL.Path, "/")
	key := keys[len(keys)-1]

	j := &scheduler.Job{}
	b, err := config.Store.Get(key, ns.Jobs...)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	if err := j.Decode(b); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	func() {
		defer func() {
			if e := recover(); e != nil {
				if er, ok := e.(error); ok {
					err = er
				}
			}
		}()
		j.Run()
	}()

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Write([]byte("{}"))
}
