package server

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

func (s *Server) Routes() error {
	wildcard := router.Wildcard
	endpoints := []struct {
		path    string
		handler http.HandlerFunc
	}{
		{
			path:    fmt.Sprintf("/upserts"),
			handler: s.gzip(s.authenticate(s.upserts)),
		},
		{
			path:    fmt.Sprintf("/list"),
			handler: s.gzip(s.authenticate(s.list)),
		},
		{
			path:    fmt.Sprintf("%s%s", wildcard, wildcard),
			handler: s.gzip(s.authenticate(s.static)),
		},
	}

	for _, endpoint := range endpoints {
		if err := s.Add(endpoint.path, endpoint.handler); err != nil {
			return err
		}
	}
	return nil
}

func (s *Server) static(w http.ResponseWriter, r *http.Request) {
	s.fileServer.ServeHTTP(w, r)
}

func (s *Server) upserts(w http.ResponseWriter, r *http.Request) {
	upsert, err := newUpsertRequest(r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	log.Println("received", upsert)
	http.Error(w, "not impl", http.StatusNotImplemented)
}

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
	}
	sort.Strings(jobs)
	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]["id"] = j.Name
		out[i]["cron"] = j.Schedule
		out[i]["language"] = j.Runner.String()
		out[i]["script"] = j.Raw
		out[i]["last"] = map[string]interface{}{
			"run":     j.LastRun,
			"runtime": j.LastRuntime,
			"output":  j.LastOutput,
			"status":  j.LastStatus,
		}
	}
	json.NewEncoder(w).Encode(out)
}
