package server

import (
	"encoding/json"
	"local/firestormy/config"
	"local/firestormy/config/ns"
	"local/firestormy/scheduler"
	"net/http"
	"sort"
)

func (s *Server) list(w http.ResponseWriter, r *http.Request) {
	jobs, err := config.Store.List(ns.Jobs)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	out := make([]map[string]interface{}, len(jobs))
	for i, job := range jobs {
		out[i] = make(map[string]interface{})
		b, err := config.Store.Get(job, ns.Jobs...)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		j := &scheduler.Job{}
		if err := j.Decode(b); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		out[i] = toMap(j)
	}
	sort.Slice(out, func(i, j int) bool {
		return out[i]["title"].(string) < out[j]["title"].(string)
	})
	json.NewEncoder(w).Encode(out)
}
